user1231561
user1231561

Reputation: 3359

How can I sent an array with $.ajax - dataType: json?

Im currently trying to sent a javascript array to my .php file handler and save it to my database.

The request is successful however it seems my array doesn't get POSTED / saved correctly. In my POST request source it just turns up as: round_items%5B%5D=1

What am I missing?

id = 5;
var roundChallenges = new Array("item1", "item2", "etc");

//Save the data
var url = path.php;

var request = $.ajax({
    type: "POST",
    url: url,
    dataType: 'json',
    data: { uid: id, round_items: roundChallenges },

    success: function(data)
    {....

Upvotes: 0

Views: 1094

Answers (1)

gen_Eric
gen_Eric

Reputation: 227240

round_items%5B%5D=1 is correct. That is what it should be sending. That decodes to round_items[]=1, which is how you make arrays in query strings.

When you pass an object to $.ajax, jQuery converts it to a query string, a standard transport format.

In PHP, you don't need json_decode or anything. It will parse it into $_POST for you. $_POST['round_items'] will be an array, and $_POST['uid'] will be your id.

Upvotes: 1

Related Questions