Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post an array using jquery ajax

Tags:

json

jquery

post

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

like image 854
Daniel Avatar asked Apr 26 '11 19:04

Daniel


People also ask

Can we send array through Ajax?

Note – You can pass JavaScript Array variable as same as any other variable in AJAX request.

What is AJAX Array?

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.

How does .post work in jQuery?

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.

What is data type in Ajax jQuery?

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.


1 Answers

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); }
});
like image 162
jerone Avatar answered Sep 24 '22 02:09

jerone