0

I have a form which I would like to submit via Ajax, however, part of it contains an array. I am having difficulty passing this array via Ajax. An example of my Ajax is below, where I would usually pass the form entry data via how it is below after data (one: $('#one').val()) where I would have one row of this for each field.

Now I have a new set of fields, where the information needs to be passed through as an array. I have tried using serialize and formData -- var fd = new FormData("#form") -- and so far either just this array has been passed through, or nothing from the form is passed through, or just the array is not passed through.

Can anyone please point me in the right direction?

$("#form").submit( function() { if (confirm('Are you sure you want to edit this?')) { $("#formMessages").removeClass().addClass('alert alert-info').html( '<img src="images/loading.gif" /> Validating....').fadeIn(500); $.ajax({ url: $("#form").attr('action'), dataType: 'json', type: 'POST', data: { one: $('#one').val(), two: $('#two').val() }, success: function(data){ //success stuff would be here } }); } return false; }); 

Thanks.

3
  • try to remove the datatype=json and pass the array in hidden element once and submit the form you should get the array values--- once check and let us know Commented Apr 27, 2015 at 12:08
  • when you use FormData, you need to set contentType:false and processData:false!! Have you done that?? Commented Apr 27, 2015 at 12:10
  • Possible duplicate of : stackoverflow.com/questions/9001526/… Commented Apr 27, 2015 at 12:12

2 Answers 2

0

You could try using :

var dataSend = {}; dataSend['one'] = $('#one').val(); dataSend['two'] = $('#two').val(); dataSend['three'] = $('#three').val(); 

then in the ajax

data: {dataSend:dataSend} 

You can gather data in php with json:

$json = json_encode($_POST['dataSend']); $json = json_decode($json); print_r($json); 

To see output.

Edit:

You can gather data in php like below:

$one = $json->{'one'}; $two = $json->{'two'}; 
Sign up to request clarification or add additional context in comments.

2 Comments

would i need to put everything i want to send into the dataSend array?
@user1842842 yes you can put all the data in the array dataSend and elaborate data in php. Look at the edits.
0

Have you tried this:

Written in JavaScript:

your_array = JSON.stringify(your_array); 

And in PHP:

$array = json_encode($_POST['array']); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.