I am trying to do something fairly simple but I can't seem to find the solution. I want to post a multi-dimensional array to a php page using jQuery's .ajax function, but I can't seem to serialize the array properly.
The code is as follows
var dataToSend = new Array();
dataToSend["page"] = location.href;
dataToSend["data"] = new Array();
var dataindex = 0;
jQuery(".myclass").each(function(){
dataToSend["data"][dataindex]=new Array();
dataToSend["data"][dataindex]["selector"] = unique_selector(jQuery(this), "");
dataToSend["data"][dataindex]["contents"] = jQuery(dataToSend["data"][dataindex]["selector"]).html();
});
jQuery.ajax({
type: 'POST',
url: "/main/save.php",
data: JSON.stringify(dataToSend),
dataType: "json",
success: function(data){alert(data);}
});
basically I am not sure how to properly pass the dataToSend array. Right now firebug show the post as empty even though the array is loaded with all kinds of good stuff.
Thanks,
Daniel
Note – You can pass JavaScript Array variable as same as any other variable in AJAX request.
DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. This can be done, in its most simple form, by setting the ajax option to the address of the JSON data source.
jQuery $.post() Method The $.post() method requests data from the server using an HTTP POST request. Syntax: $.post(URL,data,callback); The required URL parameter specifies the URL you wish to request.
The available data types are text , html , xml , json , jsonp , and script . If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
You're defining new Array();
, but you're using them as new Object()
. Try using objects.
Try this:
var dataToSend = {
page: location.href,
data: []
};
var dataindex = 0;
jQuery(".myclass").each(function(){
var temp = unique_selector(jQuery(this), "");
dataToSend.data[dataindex++] = {
selector: temp,
contents: jQuery(temp).html()
};
});
jQuery.ajax({
type: 'POST',
url: "/main/save.php",
data: JSON.stringify(dataToSend),
dataType: "json",
success: function(data){ alert(data); }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With