1

I have this frontend javascript code, that collects information (an array) and sends it to the backend. And for some reason, my php code believes this array is actually a string. Here is my javascript code :

function gamesearch() {

    var text_search = document.getElementById("search-space").value;
    var creator_search = document.getElementById("search-space-creator").value;
    var tags = document.getElementsByClassName("selectedtag");

    var tagarray = ['banana', 'fruit'];

    console.log(tagarray);
    var fd = new FormData();
    fd.append("text_search", text_search);
    fd.append("creator_search", creator_search);
    fd.append("tagarray", tagarray);
    fd.append("gamesearch", true);
    var xhr = new XMLHttpRequest();
    var fullurl = '../backend/gamesearch.php';
    xhr.open('POST', fullurl, true);
    xhr.onload = function() {
        if (this.status == 200) {

            console.log(this.responseText);

        };
    };
        xhr.send(fd);

}

And here is my backend php code

if (isset($_POST['gamesearch'])) {
  $text_search = $_POST['text_search'];
  $creator_search = $_POST['creator_search'];
  $tagarray = $_POST['tagarray'];

echo gettype($tagarray);

}

And in the console it says : string. Please help! Thanks!

2
  • Have you tried dumping $_POST['tagarray'] to see in which exact form you've received it? Commented May 2, 2021 at 14:24
  • 2
    PHP doesn't speak JavaScript and vice versa. So you'll have to encode your JavaScript to a format that both sides can interpret, like JSON. Commented May 2, 2021 at 14:27

1 Answer 1

3

Try stringifying your JSON array before sending it to the backend.

fd.append("tagarray", JSON.stringify(tagarray));

Then decode it back again in the backend

$tagarray = json_decode($_POST['tagarray']);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.