1

I'm attempting to send an array from JS to PHP using AJAX.

What seems to be happening is that the request is going through and is successful, but no data is received on the server (my test.php script needs the data from this array). Here is what I have so far...

Javascript

myButton.onclick = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "test.php", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState==4 && xhr.status==200) {
            console.log("Done. ", xhr.responseText);
        }
    }

    //xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send('myArray='+JSON.stringify(myArray));
};

test.php

<?php
//$myArray = json_decode($_POST['myArray']); //Undefined index
print_r($_POST);

Note, myArray is not shown in the above code, but it is a valid array.

I've searched around SO (which led me to adding the 'setRequestHeader' in), as well as the wider internet. However, this has made no difference and I seem to be going round in circles. When I print $_POST, it's always an empty array.

I'm sure there's something I'm missing/misunderstanding.

Edit

As requested...

var myArray = ["John", "Jill", "James"];

I've also attempted this with an array of booleans, as well as an associative array/object.

Edit 2

As requested, adding screen shot from dev console...

enter image description here

Zippy
  • 3,826
  • 5
  • 43
  • 96
  • A bullet proof solution: Create a [FormData object](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData), and set the JSON as a form property, and pass the form in `send` arguments. – Teemu Feb 28 '20 at 21:29
  • I know it's a minor thing but is myArray accessible by the function? Have you tried adding `console.log(myArray)` before `xhr.send` to ensure it's set? – Onimusha Feb 28 '20 at 21:33
  • @Onimusha, Sure it's definitely accessible by the Javascript function. Thanks – Zippy Feb 28 '20 at 21:35
  • Would you mind sharing the kind of array content? You might have to URL encode the JSON output. – geekonaut Feb 28 '20 at 21:37
  • @geekonaut, please see the edit. Thanks – Zippy Feb 28 '20 at 21:46
  • "When I print $_POST, it's always an empty array." — Are you checking the Network tab for the XHR request? (I've seen too many people follow up the XHR request with a GET request to the same URL and be surprised that it has a different response) – Quentin Feb 28 '20 at 21:51
  • 1
    Okay, so when I use the code at https://gist.github.com/AVGP/9717aeba9e9979fb1a83a982504bb82e (which is basically the code you showed us) and test it with phpFiddle, it works. Does that code work on your server? – geekonaut Feb 28 '20 at 21:54
  • @Quentin, interesting (apologies, if I'm not following 100%), when I view the header in dev console, the 'payload' does show the correct information. How do I go about getting to this information from within my PHP script? Again, apologies as I'm clearly misunderstand something. Thanks. – Zippy Feb 28 '20 at 21:59
  • What *exactly* does the payload look like? What does the response look like? It might be useful to show screenshots of the developer tools Network tab for each. – Quentin Feb 28 '20 at 22:02
  • @Quentin, please see the edit. Thank you. – Zippy Feb 28 '20 at 22:08
  • @Zippy — And the response tab for the same request? – Quentin Feb 28 '20 at 22:09
  • @Zippy that is interesting. If that is taken in Chrome, it should look differently (something like this - https://imgur.com/agGiB5Y) – geekonaut Feb 29 '20 at 13:57

1 Answers1

-3

you can use formData :

let data = new FormData();
let values = [1, 2, 3];
data.append('myArr', JSON.stringify(values));
// send data to server

and in php use json_decode :

$Values = json_decode($_POST['myArr']);

another way is to create HTML checkbox or select elements with javascript , assign values , serialize them and send them to back-end .

Iman Emadi
  • 421
  • 4
  • 14
  • The code the OP already has should work fine. Rewriting it to work this way doesn't appear to have any significant benefit. – Quentin Feb 28 '20 at 22:03
  • "you can set an array for a name" — If you mean "a name ending with `[]`" then that's a pretty-PHP-specific thing … which you aren't doing. – Quentin Feb 28 '20 at 22:03
  • Re edit: Now you are … but what's the point? You're only putting **one** value in the field. – Quentin Feb 28 '20 at 22:05
  • it's exactly how form inputs such as – Iman Emadi Feb 28 '20 at 22:06
  • Select elements with multiple values **do not** JSON encode their multiple values into a single value. – Quentin Feb 28 '20 at 22:08
  • you can `decode` and `cast` them in the `php` , right ? – Iman Emadi Feb 28 '20 at 22:10
  • The OP is already trying to decode the JSON. There is still no point is adding `[]` to the name because there is still a **single** value being sent. – Quentin Feb 28 '20 at 22:11
  • yes you are right , and there shouldn't be `[]` for the name , it will be a string value sent to back-end and then there you can decode and CAST them . i already have tried similar things , like you json_encode objects and send them to JS , you parse them and you can use them just like an Object again. i mean i think it's impossible to send a value with dataType Array directly – Iman Emadi Feb 28 '20 at 22:13