I'm using a jquery plugin called DataTables, and it requires me to return a json string in order to render the table.
Currently, the outputted json looks like this (see the aaData array):
{"sEcho":0,"aaData":[[{"ID":"1","idPatient":"122342","idFacility":"3","idTreatment":"3"}]]}
I'm wondering if the { } braces should actually be in the aaData array. In fact, I think the braces are actually what's causing the JSON parse error.
The actual code that generates this is listed below. (core->dbh is a PDO handle)
<?php
require_once('core/Core.php');
$core = Core::get_instance();
$sql = 'SELECT ID, idPatient, idFacility, idTreatment
FROM Pathology WHERE idPatient = 122342';
$stmt = $core->dbh->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// bind parameters
$stmt->execute();
// prepare output for DataTables
$data = array("sEcho" =>intval($_GET['sEcho']),
"aaData" =>array()
);
while($result = $stmt->fetchAll()) {
$data['aaData'][] = $result;
}
echo json_encode($data);
?>
Could someone please tell me how can I remove the curly braces, or if the JSON is improperly formatted in another way that could be causing the parse error?
Thanks
The JSON is fine. You are encoding it with PHP via json_encode, that can't be the problem. My guess would be that by doing this $data['aaData'][] = $result; you are nesting twice (see the double brackets) your results and the plugin fails. Try this: $data['aaData'] = $result;
Related
I made a script to return IDs to me based on if a point is within a polygon. Currently this works when I invoke the script on my DB or on Postman, though when I invoke it else where it does not work.
I've looked into the post request body and 'Coordinates' is not a geography it is and encoded version (my guess), which I've tried to unpack within the query which hasn't worked. The only way I was able to unpack it within a different query was st_asgeojson and then use json_decode on the result but I want this to be done in one query.
Coordinates is passed as the following code:
"0101000020E6100000000000000040604000000000000039C0"
I want to convert this either outside the query or within it, to then get the results from my query. My PHP code is as follows:
<?php
require_once('../db.php');
$rawdata = file_get_contents("php://input");
$decoded = json_decode($rawdata, true);
$coordVar = handleCoords($decoded['event']['data']['new']['Coordinates']['coordinates']);
$res = pg_query_params($conn, 'SELECT "ShapeID" FROM "Shapes" WHERE st_within( ST_SetSRID( ST_MakePoint($1, $2), 4326), "Coordinates"::geometry) ', array($coordVar[0], $coordVar[1]));
while ($row = pg_fetch_assoc($res) ){
print_r($row['ShapeID]);
}
function handleCoords($data) {
return array($data[0], $data[1]);
}
?>
When testing my queries I obtained "Coordinates" from one of my tables which was a bytea code when looking at the results, as this is a geography data type. I got around this by using the ::geometry conversion, thinking about this, the issue I had was a simple fix. As the coordinates passed through the POST request body was also of the same data type, geography, therefore applying the same conversion would allow the query to work when invoked from any application.
The code is as follows:
<?php
require_once('../db.php');
$rawdata = file_get_contents("php://input");
$decoded = json_decode($rawdata, true);
$coordVar = handleCoords($decoded['event']['data']['new']['Coordinates']);
$res = pg_query_params($conn, 'SELECT "ShapeID" FROM "Shapes" WHERE st_within( ST_SetSRID( $1::geometry, 4326), "Coordinates"::geometry) ', array($coordVar));
while ($row = pg_fetch_assoc($res) ){
print_r($row['ShapeID]);
}
?>
I tried to make json file to convert my data from database to json and ended up with error (SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)
when i use a database which not containt img_url it could work but when there is img_url always error.
i tried using .php extension and it works but the img_url is a mess but when i use .json extension it shows the error
this is my code:
$stmt = $conn->prepare("SELECT namajurusan, fakultas, deskripsi, img_url FROM tbl_prodi;");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($namajurusan, $fakultas, $deskripsi, $img_url);
$prodi = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['namajurusan'] = $namajurusan;
$temp['fakultas'] = $fakultas;
$temp['deskripsi'] = $deskripsi;
$temp['img_url'] = $img_url;
array_push($prodi, $temp);
}
//displaying the result in json format
echo json_encode($prodi);
Make sure you are not sending unparsed strings to your JSON before calling json_encode.
Try to see it using var_dump().
Encode the url using urlencode before adding it to the json.
PHP Docs: http://php.net/manual/en/function.urlencode.php
Update:
Instead of using array_push($prodi, $temp); use $prodi[] = $temp.
So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]
here is my code
<?
include '../dbConnect.php';
$amp=trim($_POST['amp']);
//$amp='AMP8';
//$sql=mysql_query("select tblRepairQueue.ackNo,tblRepairQueue.repairStatus,tblRepairQueue.savedAt from tblRepairQueue,AMPcustomers where AMPcustomers.phone1=tblRepairQueue.phoneNo and AMPcustomers.id='".$amp."'");
$sql=mysql_query("select phone1 from AMPcustomers where id='".$amp."'");
$response = array();
while($row=mysql_fetch_array($sql))
{
$sql_query=mysql_query("select ackNo,repairStatus,savedAt from tblRepairQueue where phoneNo='".$row['phone1']."'");
while($row1=mysql_fetch_array($sql_query)){
$ackNo=$row1['ackNo'];
$repairStatus=$row1['repairStatus'];
$savedAt=$row1['savedAt'];
$response[]=array('ackNo'=>$ackNo,'repairStatus'=>$repairStatus,'savedAt'=>$savedAt);
}}
print json_encode($response);
?>
output m getting as
{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
but i want the output to look like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
Can anyone plz help in finding the mistake or what has to be done to get square brackets at the end
This is a bit strange because I have this code:
<?php
$array = array();
$array[] = array("ackNo"=>"26101211236759","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 00:55:25");
$array[] = array("ackNo"=>"26101211236780","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 10:55:25");
echo json_encode($array);
?>
And I get this correct form:
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"26101211236780","repairStatus":"Closed and Complete","savedAt":"2012-10-26 10:55:25"}]
This code should indeed output [{...},...]. So we can't really tell you what went wrong on your side. check the structure of the $response variable before the conversion to Json to see what went wrong.
Note that the code allows SQL injection. You must change it so that the parameters $amp and $row['phone1'] are escaped in the SQL queries. Even if you're relying on magic qoutes now, this solution is not future-proof (now-proof really) as support for this is was removed in PHP 5.4.
What you have written should work:
http://ideone.com/ErV9fr
// How many to add
$response_count=3;
// Your response, just templated
$response_template=array(
'response_number'=>0,
'ackNo'=>'dffdgd',
'repairStatus'=>'$repairStatus',
'savedAt'=>'$savedAt'
);
// Your empty response array
$response = array();
for($i=0;$i<$response_count;$i++) {
$response_template['response_number'] = $i; // Set the 'response number' to the itteration.
$response[]= $response_template; // Add the template to the collection
}
print json_encode($response);
Result:
[{"response_number":0,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":1,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":2,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"}]
In addition to this, you should sanitize your $amp variable. In it's current form it would be trivial for a user to escape your query and execute an arbitrary query against your DB.
http://www.php.net/manual/en/mysqli.real-escape-string.php
Please recheck it can not give you the output like that {"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
as it is creating an array of array so it can not print like that.
It will always print like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
I have this code converting a mysql query to json:
$sth = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Works great, but i have in my database, a url field, here is a sample json row:
{"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"},
How can i get around this?
I suppose the "problem" is the presence of backslashed in the URLs ?
Like :
http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg
Well, that's not a problem for Javascript : try to assign your JSON data to a Javascript object, and display one of those URL :
var data = {"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"};
alert(data[3]);
The URL is displayed correctly :
http://images.apple.com/webapps/productivity/images/noter2_20091223182720-thumb.jpg
So, the backslashes are not a "problem" ;-)
And, in fact, if you take a look at the "string" section of json.org, you'll see that slashes have to be backslashed for your string to be valid.
I don't see a problem here. If you're wondering why the URLs look like this:
http:\/\/www.example.com\/
Instead of like this:
http://www.example.com/
It's because the / characters are being appropriately escaped. When you unserialize the JSON object in javascript, the URLs will look as they do in your database.