Homer Homer - 1 year ago 171
jQuery Question

PHP return JSON to Ajax works on localhost only

I've a simple contact form, and using Ajax to process it with a PHP file...

The problem is: it works just fine on the localhost, but it does NOT on the live server!, it gives me on the console:

[object Object]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

This is my code:


if (isset($error) && !empty($error)) {
exit(json_encode(["error" => $error]));


exit(json_encode(["success" => "success message"]));

jQuery Ajax:

url: "./includes/form-processor.php",
method: "POST",
data: data,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if ('undefined' == data.error || data.error == null) {
} else {
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR + "\n" + textStatus + "\n" + errorThrown);

I've read a lot of similar questions here on stack overflow but most of the answers for them mentioned that it happens because they're parsing the data JSON by jQuery and return it from the back-end as JSON again!

So, actually that make me not sure if I'm returning it from the PHP file right or not!

I've tried to return it from the PHP this way:

exit(["success" => "success message"]);


exit("success" => "success message");


exit("success message");

But it doesn't work as well!

Also, as I said earlier

it works just fine on the localhost, but it does NOT on the live server!

So, that sounds weird! o.O

What should I check to make it works on the live server?



["success" => "success message"] is a new array syntax introduced in PHP 5.4 so your production server is probably under 5.4. You should use array("success"=>"success message") instead. For your specific code, use:

exit(json_encode(array("success" => "success message")));


exit(json_encode(array("error" => $error)));