skip to Main Content

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?

2

Answers


  1. Because you are echoing the print_r() (which in and of itself is a type of echo) you’re returning a value for the truthiness of the print_r(). Change the line to this

    print_r($_POST['usedAnswers']);
    
    Login or Signup to reply.
  2. 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);
                }
            });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search