Saturday 10 November 2012

Sending data from object using jQuery ajax / post

Hi,

Recently I stumbled upon a problem to send an object created in javasctipt using jQuery ajax method. As I searched on internet, I found many answers suggesting to use JSON.stringify(object) method to send the data. But the fact is it doesn't work as you want it to work.

For example here is the object that I want to send to php.
var objReqData = new Object();
objReqData.page = 1;
objReqData.type = 1;
So this is the data you want to send to php. So ideal on php side you would like to receive it on $_POST variable (I am using post method) like $_POST['page'] and $_POST['type'].

Now if you use JSON.stringify() method, your request would be something like this

   $.ajax({ url: ajax/request.php, 
type: "POST",
      //Yes you can not simply use "data: JSON.stringify(objReqData)", if you use it that way you will not receive any post data
data: { params : JSON.stringify(objReqData) },  
success: function(data) {
     console.log(data);
},
error:  function(data) {
console.log(data);
}
});


So using this request on php side you will receive the data in $_POST['params'] variable not like you want to have it in straight $_POST['page'] and $_POST['type'] variables. Here $_POST['params'] variable will hold the json encoded values of page and type. So you again have to json_decode it in php.

But this is not the ideal solution. After much of research the best solution I found out was much simpler. You only need to use jQuery.param() method to serialize your object and that's it. Here is what I used.



   $.ajax({ url: ajax/request.php, 
type: "POST",
data: jQuery.param(objReqData) ,  //Yes this is all you need to write
success: function(data) {
console.log(data);
},
error:  function(data) {
console.log(data);
}
});

Using this request you receive the post data in variables $_POST['page'] and $_POST['type'], the way you most probably want to have them.

No comments:

Post a Comment