2

I have an array of which each element is an array, like so:

results = {
              {1, "A", 11, 0, 7, 0},
              {2, "A", 13, 2, 2, 1},
              {3, "A",  7, 0, 2, 2}
          }

And I was wondering how I could send this to PHP via jQuery's .ajax function?

My jQuery call at the moment looks like:

$.ajax({type: "POST",
        url:  "updateResults.php",
        data: "results="+results,
        success: function(data) {
            if(data == "ok") {
                $("#msgSuccess").show();
            } else {
                $("#msgError").show();
            }
        }
});

Thanks!

Chris Matthews
  • 382
  • 4
  • 19
  • 4
    This is not correct JavaScript. Maybe you meant `[]` instead of `{}`? It depends on in which format you want to send the data. The simplest would be `data: {results: results}`, or you serialize it as JSON. – Felix Kling Dec 20 '11 at 11:33
  • This is a duplicate of http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery It basically tells to use the stringify method as shown below, in fact recommended by John Resig. var json_text = JSON.stringify(your_object, null, 2); – Sunil Bannur Dec 20 '11 at 11:36
  • Duplicate Question : [http://stackoverflow.com/questions/2032044/jquery-post-multidimensional-array-via-ajax](http://stackoverflow.com/questions/2032044/jquery-post-multidimensional-array-via-ajax).. – Chandresh M Dec 20 '11 at 11:38
  • @FelixKling - Yeah, sorry, stupid error while posting the question - it uses [] in my code! – Chris Matthews Dec 20 '11 at 12:05
  • Please check this article: [Send multidimensional arrays to PHP with jQuery and AJAX](http://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/) , it will help you a lot... – Md Jawed Shamshedi Dec 20 '11 at 11:40

3 Answers3

2

use serializeArray() http://api.jquery.com/serializeArray/

2

The easiest is to use an object for data:

data: {results: data};

jQuery will automatically URI-encode the data if you do so, which is more advantageous than messing around with string concatenation yourself.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

If the results is in string format then this works Fiddle

var results = '{{1, "A", 11, 0, 7, 0}, {2, "A", 13, 2, 2, 1}, {3, "A",  7, 0, 2, 2}}';
results = results.replace(/{/gi, '[');
results = results.replace(/}/gi, ']');
results = eval(results); //This is your array format which can be sent as JSON request data

$.each(results, function(index, item){
    $.each(item, function(ind, it){
        alert(it);
    });
});
Sandeep G B
  • 3,957
  • 4
  • 26
  • 43