Currently I have an ajax setup where my page with javascript calls a php file which then returns data via xhttp.responseText. This works great for strings but when I pass it a json encoded array, it still views that results as text. I get a string formatted version of my array that looks like this [1,2,3,4,5,6,7]
Which sort of works, but it's inconvenient because it's text representing an array and not an actual array.
How can I receive the data as an array instead of an array in text format? Currently I can still get the data using split(), but that seems sloppy. Is there an alternative to xhttp.responseText that would work better?
You can try sending your data as a JSON, which will give you all the flexibility in the kind of structure you want the data to have. PHP has the function json_encode which will convert your PHP variable into a JSON and you can receive this on the client side.
First, make sure your PHP encodes the JSON as I said and that you have the proper header set too, i.e. header('Content-Type: application/json');
Next, in your AJAX code, do JSON.parse(xhttp.responseText) to retrieve the JSON data as JavaScript object.
Then you can do whatever you want with this object. Also, you can check your PHP is sending a JSON via xhttp.getResponseHeader("Content-type") which should return "application/json" if you are sending a JSON object.
You need to set header, smth like following
$data = array('1', '2', '3');
header('Content-Type: application/json');
echo json_encode($data);