I am trying to write an Ajax request using JavaScript (without jQuery) and related to this tutorial, I have this function now:
function postAjax(url, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
and I can send data using JSON format like this:
postAjax(MY_SERVER_URL, { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });
and on the server, I only have print_r($_POST)
, then the output is:
Array
(
[p1] => 1
[p2] => Hello World
)
But when I have a nested JSON, it will show me [object Object]
as output instead of each array and object in my JSON. for example:
postAjax(url, { p1: 1, p2: {'test_name':'Hello World'} }, function(data){ console.log(data); });
Output:
Array
(
[p1] => 1
[p2] => [object Object]
)
Can you please guide me how I should convert a nested JSON to a URL query string to pass by AJAX?
Update
Please note that I can convert whole of my nested JSON to a string using JSON.stringify
and pass it to the server, but as you probably know, if I use some libraries like jQuery, you can send nested JSON to the server and you don't need to decode the string on the server. the point of this question is exactly how some library like jQuery is passing data to the server that you can get it directly without any decoding?