Search code examples
cakephpcakephp-1.2

Couldn't receive any data using jQuery AJAX in CakePHP


I am using CakePHP 1.26.

I was trying to use jQuery Ajax to pass some sample data to a function in a Controller but failed to do it.

This is the jQuery part:

 var w="helloworld";
 var curl="http://localhost:8080/test/grab/";
 $.ajax({
     type: "POST",
     url: curl,
     data: "testing="+w,   
     success: function(data) {    
         alert(data);
     }
 });

And this is the function of the Controller:

function grab() {
    $g=$this->data['testing'];
    return $g;
}

But the alert msg box did not show me anything but a blank message.

Please help if you could.


Solution

  • $this->data is only filled with data in the format data[key]=value. In this case, your AJAX call's data property should look like this:

    data: "data[testing]=" + w
    

    To pass more than one, simply separate with an ampersand:

    data: "data[one]=" + one + "&data[two]=" + two
    

    Finally, you can actually nest them, like so:

    data: "data[0][one]" = one[0] + "&data[0][two]=" + one[1] + "&data[1]=" + data
    

    This will make $this->data a multi-dimensional array.