Returning Json from a PHP Script

Returning JSON from a PHP Script

While you're usually fine without it, you can and should set the Content-Type header:

<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);

If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).

Return JSON object from php script

In your PHP file, change the content type to application/json.

JS

$.get('/process.php', function(data) {      
console.log(data);
} );

PHP

<?php

header( "Content-type: application/json" );

$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);

Then your console should read Object {test: "true"} rather than just the JSON string.

Return json data with php

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);
}
}
});
});

Returning JSON from PHP to JavaScript?

Php has an inbuilt JSON Serialising function.

json_encode

json_encode

Please use that if you can and don't suffer Not Invented Here syndrome.

Return JSON from PHP script

Check the JSON Errors using json_last_error(). Possibly there's a character which cannot be put inside JSON. I encountered a same issue and I used this code:

<?php
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
?>

You can make something like:

$array = utf8ize($array);

simple php script, unable return json

I don't know why do you need a database connection here, but I think I know where is the mistake. You're displaying text that is not json here: print('connesso db -- '); If you expect a json format, you should display everything only in json format. Even on the failed connection possibility.
Here is how I would write it:

<?php
$host = "127.0.0.1";
$user = "test";
$password = "123456789";
$database = "nx_database";

header('Content-Type: application/json');

try{
$pdo = new PDO ("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo json_encode(['error' => "DB Connection Fail" . $e->getMessage()]);
exit;
}


$staff = $_POST['staff_ID'];

$array = [
'isLoggedIn'=>$staff
];
$js = json_encode($array);

echo $js;

?>

How to return json string from php array

You need to set the response headers, and ensure you are not violating CORS:

    /*
* Construct Data Structure
*/
$response =
[
'value1',
'value2'
];

/*
* Format Data
*/
$jsonResponse = json_encode ( $response, JSON_PRETTY_PRINT );

/*
* Prepare Response
*/
header('content-type: application/json; charset=UTF-8');

/*
* ONLY if you want/need any domain to be able to access it.
*/
header('Access-Control-Allow-Origin: *');

/*
* Send Response
*/
print_r ( $jsonResponse );

/*
* Return with intended destruction
*/
die;

Return JSON data from PHP script using AJAX jQuery

You can give a "json" argument to $.post to tell it that the response is JSON, and it will automatically parse the response to a Javascript object or array. In my sample code below I'm assuming it's an array, and each element is an object that contains a property that you want to show in the result; replace .someProperty with the actual property.

$("#computerForm").submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(info) {
var html = "";
$.each(info, function() {
html += this.someProperty + "<br>";
});
$("#result").html(html);
}, "json");
});

process.php can use $_POST['serialnumber'] when it's calling the Airtable API.

$sn = $_POST['serialnumber'];

returning JSON and HTML from PHP script

Don't echo the line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
);
and send that back ( via json_encode ) instead.

Also, you don't need json2.js, jQuery has an excellent JSON parser.

you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );

Changed to match your newly introduced iteration.

for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array(
"name" => stripslashes($row["name"]),
"comment" => stripslashes($row["comment"]),
"datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
);
}

$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";

echo json_encode(array( 'comments' => $comments, 'html' => $html ));

then, in your javascript, you have

function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}


Related Topics



Leave a reply



Submit