Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an Ajax variable to a Codeigniter function

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.

like image 465
Matt Avatar asked Jan 22 '23 03:01

Matt


1 Answers

   $("#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.

like image 112
Teej Avatar answered Jan 24 '23 17:01

Teej