Reputation: 115
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
Upvotes: 2
Views: 7135
Reputation: 95030
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;
Upvotes: 3
Reputation: 115
It was solved by changing the Javascript to:
answers = {};
I could then simply access the data in PHP with:
$_POST['answers'][1]['answer_id'];
for example, or just loop through it.
Thanks for your help, ladies and gentlemen.
Upvotes: 1
Reputation: 4320
You can collect the value in php page with $_POST['answers']
. Then you can loop through that array do whatever you want with the data.
Upvotes: 1