Return json data with php

I want to return json data, but my code is not working. I am not getting an error message. I have index.php, ajax.php and db.php. Db.php is working. But my ajax code is not working. Where is my mistake?

index.php:

<!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> </head> <body> <div id="test" style="width:500px;height:400px; margin:20px auto;"></div> <script> $(window).load(function () { $.ajax({ dataType: "json", url: 'ajax.php', success:function(data){ $("#test").html(data); } }); }); </script> </body> </html> 

Ajax.php:

 <?php require 'db.php'; $query="select lat,lng from locations order by id"; $result = pg_query($link, $query); if (!$result) { echo "An error occurred_xxx.\n"; }else { $arr = pg_fetch_all($result); echo json_encode($arr); } ?> 
+6
source share
1 answer

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); } } }); }); 
+6
source

All Articles