Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return json data with php

Tags:

json

php

I want to return json data but my code is not working. I don't get any 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);
}  ?>
like image 864
Mike Henley Avatar asked Jun 20 '16 00:06

Mike Henley


People also ask

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What is JSON response in PHP?

JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.

How can access JSON decoded data in PHP?

Reading JSON From a File or String in PHP First, you need to get the data from the file into a variable by using file_get_contents() . Once the data is in a string, you can call the json_decode() function to extract information from the string.


1 Answers

If you're expecting JSON you need to send it regardless. What you're doing when your script errors, is sending text/html. Try this:

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'll see, we send actual JSON, by setting a correct Content-Type header and not mixing plain text and json up.

To handle this response within your jQuery, simply condition the response:

$(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);
            }
        }
    });
});
like image 121
Darren Avatar answered Oct 14 '22 21:10

Darren