Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 411
Gihan Lasita Avatar asked Jul 04 '26 22:07

Gihan Lasita


1 Answers

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

like image 66
Edgar Villegas Alvarado Avatar answered Jul 06 '26 13:07

Edgar Villegas Alvarado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!