If you expect JSON , you need to send it independently. What do you do when your script errors send text/html . Try the following:
header("Content-Type: application/json"); require 'db.php'; $query="select lat,lng from locations order by id"; $result = pg_query($link, $query); $response = array(); if (!$result) { $response = array( 'status' => false, 'message' => 'An error occured...' ); }else { $response = array( 'status' => true, 'message' => 'Success', 'data' => ph_fetch_all($result) ); } echo json_encode($response);
Now, as you will see, we are sending the actual JSON by setting the correct Content-Type header and not mixing plain text and json up.
To process this answer in your jQuery, just specify the answer:
$(window).load(function () { $.ajax({ dataType: "json", url: 'ajax.php', success:function(data){ if(!data.status) { $("#test").html("ERROR: " + data.message); } else if(data.status) { $("#test").html(data); } } }); });
source share