Homer Homer - 6 months ago 61
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]
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data


This is my code:

PHP:

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


And

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


jQuery Ajax:

$.ajax({
url: "./includes/form-processor.php",
method: "POST",
data: data,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
console.log(data);
console.log(data["error"]);
console.log(data.error);
if ('undefined' == data.error || data.error == null) {
message_window.text(data["success"]);
} else {
message_window.text(data["error"]);
}
},
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"]);


And

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


And

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?

Thanks

Answer

["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")));

and

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