Gihan Lasita
Gihan Lasita

Reputation: 3053

how to create javascript array contain key and value?

there is few text boxes im generating dynamically with a counter so its looks like this

form.append('Street: <input type="text" id="street'+counter+'" /> city: <input type="text" id="city'+counter+'" /><br/>'); 
counter++;

then im doing this to make a array

var array = [];
for(i=1; i<counter; i++){
array.push({'a':$('#street' + i).val(),'b':$('#city' + i).val()});          
}   
console.log(array);
$.ajax({
  type: "POST",
  url: "dummy.php",
  data: array,
  success: function(response, textStatus, xhr) {
  },
  error: function(xhr, textStatus, errorThrown) {
  }
});

but the problem is when im trying to send array to php script via ajax im getting Parameters undefined undefined undefined undefined

in post section of firebug

what im doing wrong here?

firebug console looks like with console.log(array) firebug output

Regards

Seems like i found the solution i sent data like data: {Addresses:array}, and it works

Upvotes: 3

Views: 566

Answers (1)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

You could send your form as-is like this (don't send as array):

$.ajax({
  ...
  data: form.serialize()
  ...
});

and turn it to an array in your server code.

Or, alternatively, you could name your inputs in a way they will automagically become two arrays on the server:

form.append('Street: <input type="text" name="street[]" /> city: <input type="text" name="city[]" /><br/>'); 
$.ajax({
  ...
  data: form.serialize()
  ...
});

And your PHP script would recieve $_POST['street'] and $_POST['city'] as arrays. Hope this helps. Cheers

Upvotes: 2

Related Questions