views:

125

answers:

1

Hello,

I think this is a simple one.

I have a Codeigniter function which takes the inputs from a form and inserts them into a database. I want to Ajaxify the process. At the moment the first line of the function gets the id field from the form - I need to change this to get the id field from the Ajax post (which references a hidden field in the form containing the necessary value) instead. How do I do this please?

My Codeigniter Controller function

function add()
{
    $product = $this->products_model->get($this->input->post('id'));

    $insert = array(
            'id' => $this->input->post('id'),
            'qty' => 1,
            'price' => $product->price,
            'size' => $product->size,
            'name' => $product->name
        );

    $this->cart->insert($insert);
    redirect('home');
}

And the jQuery Ajax function

$("#form").submit(function(){
        var dataString = $("input#id") 
        //alert (dataString);return false;  
        $.ajax({  
            type: "POST",  
            url: "/home/add",  
            data: dataString,  
            success: function() {

            }  
        });
        return false;
    });

As always, many thanks in advance.

+2  A: 
   $("#form").submit(function(){
        var dataString = $("input#id") 
        //alert (dataString);return false;  
        $.ajax({  
            type: "POST",  
            url: "/home/add",  
            data: {id: $("input#id").val()},  
            success: function() {

            }  
        });
        return false;
    });

Notice data option in the ajax method. Now you could use $this->input->post('id') like you are doing in the controller method.

Thorpe Obazee
Thanks Thorpe, very useful to know. I just need to change the first line of the codeigniter function so that it isn't looking for the form input, but the jquery ajax
Matt
"Form inputs" and "AJAX variables" are the same thing, they are both POST parameters sent over an HTTP request. AJAX is not a "thing" that exists, just the name of a methodology.
Phil Sturgeon