Chris Matthews
Chris Matthews

Reputation: 382

Send nested array via jQuery .ajax

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!

Upvotes: 2

Views: 2589

Answers (3)

Sandeep G B
Sandeep G B

Reputation: 4015

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);
    });
});

Upvotes: 0

pimvdb
pimvdb

Reputation: 154838

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.

Upvotes: 2

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

Upvotes: 2

Related Questions