Im trying to send an array to the PHP script:
usedAnswers = [1,2];
// funtion for displaying a question
displayQuestion = () => {
$.ajax({
url: "backend/retriveData.php",
data: {usedAnswers:usedAnswers} ,
type:"post",
success: function(response) {
console.log(response);
}
});
}
// inital display of question
displayQuestion();
Then when I want to access the array in the PHP script
<?php
echo print_r($_POST['usedAnswers']);
?>
I get the following problem on screen
Why is he adding an extra 1 ?
When I try to access the first element of the Array like this:
echo print_r($_POST['usedAnswers'][0]);
He console.logs me the number 11?
What am I doing wrong what is the correct way to send an Array via Ajax?
Is it also possible to send a set via Ajax?
2
Answers
Because you are echoing the
print_r()
(which in and of itself is a type ofecho
) you’re returning a value for the truthiness of theprint_r()
. Change the line to thisso, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you’re getting, which Jay has already answered for you.
as far as your code reads, what you’re actually sending is this:
which is invalid JSON.
if you’re trying to actually have a ‘usedAnswers’ key (which it looks like from your php), then you need to do this: