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;
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.