Wednesday, 29 August 2018

Passing a multidimensional array to PHP with jQuery and AJAX

I've got the jQuery code:

$(document).ready(function() {

answers = new Array();

answers[0] = new Array();
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;

answers[1] = new Array();
answers[1]['question_id'] = 55;
answers[1]['answer_id'] = 132;

answers[2] = new Array();
answers[2]['question_id'] = 987;
answers[2]['answer_id'] = 1112;

$.ajax({
    type: "POST",
    url: "collect.php",
    data: {answers: answers},
    dataType: "json",
    beforeSend:function(){
        // Do something before sending request to server
    },
    error: function(jqXHR, textStatus, errorThrown){

        alert(errorThrown);
    },
    success: function(data){

        alert('success!');
    }
});

});
Now, should this work? According to what I've found when looking for code examples it should. Problem is, I have no idea how I could collect the data in my PHP file. I mean, it's a $_POST[], but then what? How do I collect the $result[0]['question_id'] and all the other data?
Thanks a lot in advance,
Carl C. Carlsson

You're never actually populating the arrays inside of the answers array with data, their length is still 0 because you're using string indexes rather than int indexes. What you really want are objects stored in your array.
answers[0] = {};
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;

0 comments:

Post a Comment