I apologise, since I know this has been asked before, more than once.
I've been struggling with this little bugger for quite a few hours now, and I cannot seem to find my mistake.
The problem is simple - I have a PhP array which I want to pass over, from the server side to the client side, using jQuery AJAX with the data in JSON format.
The code for my Client-side Ajax call is
$.ajax({
url: 'php/test/pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
And the code for my server-side pass_array.php script is
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name"=>"Johnny")); //Build JSON object from the array
As you can see, this is pretty basic, but it's not working. On the client side, the AJAX response is never received.
When I check the browser console log, I get
Error: SyntaxError: Unexpected token parsererror [object Object]
What the devil am I doing wrong?
All my files are in UTF-8 encoding. This also works if I remove the dataType: 'json' and the heading() on the PhP side. In that case, I get the following string:
{"Name":"Johnny"}
UPDATE
Commenting out the header() code in the PhP side makes the console show the following error:
Uncaught SyntaxError: Unexpected token o
How can there by syntax errors? I create a PhP array and encode it using json_encode.
UPDATE #2
Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
It looks like including that db_io.php file added a Byte Order Mark character (\ufeff) to the JSON string.
The complete string being sent to the Client side was
\ufeff{"Name":"Johnny"}
It seems this db_io.php file was encoded with BOM. Changing its encoding (using notepad++) fixed that.
Amazing how a simple include instruction can mess up an AJAX call.