Sending an array/set via to PHP via $.ajax. PHP adding a number

Fabian Andiel :

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

enter image description here

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?

DevDonkey :

so, 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:

{[1, 2]:[1, 2]}

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:

        $.ajax({
            url: "backend/retriveData.php",
            data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
            type:"post",
            success: function(response) {
                console.log(response);
            }
        });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=342501&siteId=1