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.

ilter
  • 4,030
  • 3
  • 34
  • 51
user1842842
  • 95
  • 1
  • 2
  • 14
  • 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 – Neelesh Apr 27 '15 at 12:08
  • when you use `FormData`, you need to set `contentType:false` and `processData:false`!! Have you done that?? – Guruprasad J Rao Apr 27 '15 at 12:10
  • Possible duplicate of : http://stackoverflow.com/questions/9001526/send-array-with-ajax-to-php-script – Alex Apr 27 '15 at 12:12

2 Answers2

0

Have you tried this:

Written in JavaScript:

your_array = JSON.stringify(your_array);

And in PHP:

$array = json_encode($_POST['array']);
Eel Lee
  • 3,513
  • 2
  • 31
  • 49
Lazar Bulatovic
  • 169
  • 1
  • 1
  • 9
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'};
Alex
  • 626
  • 7
  • 16