0

I am getting my form data in to a array with

var fields = $(this).serializeArray();

I want to push the dynamic token value to this array before I make ajax call to process this array in php.

I try with

fields.push({token:value});

my ajax call to php is

$.ajax({

    type : 'POST',
    url : "test.php",
    data : fields,
    dataType : 'json',
    success: function(data) {......},
    error{....}
});

In my test.php page I want to use that token value like

 $token = $_POST[token];

but the $token value is null.

VDN
  • 85
  • 1
  • 9

2 Answers2

2

.serializeArray returns an array with the structure

[{name: 'name', value: 'value'}, ...]

So you have to add an object with name and value properties:

fields.push({name: 'token', value: 'value'});

Or if token and value are variables:

fields.push({name: token, value: value});

Have a look at the documentation for more information.

I have already answered that in another question: Can I add data to an already serialized array?.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Try this:

fields[token] = value;

If you use push, you're just pushing a value onto the end of the array, and the last index will just increment.

Richard
  • 4,341
  • 5
  • 35
  • 55
  • If it would have been an object it would be `fields.token = value;`. It is correct – Richard Jun 03 '13 at 20:34
  • No! Whether you use dot notation or bracket notation does not matter. I assume `token` contains a string... do you use string keys with arrays? I hope not. – Felix Kling Jun 03 '13 at 20:34
  • If I use this ajax call fails. – VDN Jun 03 '13 at 20:35
  • Why assume `token` is a string? `fields` is an array regardless... Token could be anything. – Richard Jun 03 '13 at 20:37
  • I don't assume anything. Topic poster is using an array and wants an item added onto it, apparently with a unique identifier. – Richard Jun 03 '13 at 20:38
  • You can add elements to the array this way **if and only if** `token` is a number. But the problem is that `fields` is an array with a very **specific** structure and it has to have this structure if you want to make it work with `$.ajax`. Doing `fields[token] = value;` does not keep the structure. See my answer. – Felix Kling Jun 03 '13 at 20:40
  • @FelixKling that's blatantly wrong. arrays ARE objects in javascript, and you can add properties to arrays just like you'd add them to any other object. – user428517 Jun 03 '13 at 20:44
  • @sgroves: I never said arrays are not objects (well ok, I wanted to point out that `fields` should be treated as array and not as plain object). You shouldn't add properties with non-numeric names to it like this. They will all be ignored by array methods. And in any case, even if `token` was a numeric value, it wouldn't help the OP. The array has a specific structure as I already said a couple of times. – Felix Kling Jun 03 '13 at 20:45