Parsing JSON : unexpected character - php

This question is related to a previous one I wrote here.
Is this JSON syntax correct ? I need it to make a jqPlot chart after.
[{"Date":"2012-02-29","Close":"87.60"},{"Date":"2012-02-28","Close":"87.77"},{"Date":"2012-02-27","Close":"88.07"}]
I ask this because I can't use jQuery.parseJSON(jsonString); or JSON.parse(jsonString); with this string. Firefox returns :
SyntaxError: JSON.parse: unexpected character # index2.php:677
Here is the PHP code that generates it :
<?php
$req = $bdd->prepare('SELECT Date, Close FROM quotes WHERE Symbol = ? AND Date > ? AND Date < ?');
$req->execute(array($_GET['id'], $_GET['datemin'], $_GET['datemax']));
$test=array();
while ($donnees = $req->fetch(PDO::FETCH_ASSOC))
{
// echo print_r($donnees) . "<br />";
// echo $donnees[Date] . "<br />";
$test[] = $donnees;
}
echo json_encode($test);
?>
I don't know what's wrong.
EDIT : Javascript code added.
<script>
$("button").click(function(){
$.get("requete_graph.php", {
id: param1,
datemin: param2,
datemax: param3
}, function(data,status){
console.log(data);
make_graph(data);
}, "json");
});
function make_graph(toto) {
alert("String before : " + JSON.stringify(toto));
var json_parsed = JSON.parse(toto);
alert("String after : " + JSON.stringify(json_parsed));
$(document).ready(function(){
var plot1 = $.jqplot('chartdiv', json_parsed);
});
}
</script>

The JSON is indeed valid (you can check it at jsonlint.com
Your problem might be arising due to extra non whitespace characters being sent after the JSON (for example: PHP errors/warnings). A good way to guarantee that nothing else is output after your JSON is using PHP's die function to send content then stop executing.
die(json_encode($test));
// OR
echo json_encode($test);
die();

At the top of your PHP script, add:
header('Content-type: text/json; charset=utf-8');
If you don't have it, the server will send it as plain text, and your browser won't know that it is a json string.

jQuery.get, given the right dataType parameter (which you did) or a content-type header, does already parse the JSON for you. Your callback function receives an array as the data parameter, not a string.
var json_parsed = JSON.parse(toto);
will then throw an error as toto is not a JSON string (your FF seems to .toString() the array, and then encounters and invalid character). Instead, just use
function make_graph(toto) {
console.log(typeof toto, toto);
alert("String before : " + JSON.stringify(toto));
var json_parsed = toto; // or just use `toto` everywhere
$(document).ready(function(){
var plot1 = $.jqplot('chartdiv', json_parsed);
});
}

Related

Javascript, PHP, AJAX: how to echo arrays and append them into a html division

I am a beginner and I am trying to echo arrays and append them into a html division i created. The AJAX call I made was successful but the response was not appearing inside the division i assigned it to. Upon further inspection, I found out that the response I have received has an array length over 600 ( I am expecting 10 records). So there must be something wrong with my echo PHP file or the receiving end of the HTML file but just cannot figure out what that is.
Here are my codes:
listdiscount.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "root", "bencoolen");
$userid = $_GET['userid'];
$result = $conn->query("select userid, codename from discountcode where userid ='" . $userid . "' ");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
printf("Userid: %s '' Codename: %s", $row["userid"], $row["codename"]);
}
$conn->close();
?>
index.html ( with js codes )
<html>
<script>
function mydiscount(){
var userid = "jimmy";
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/listdiscount.php";
url += "?userid=" + userid;
alert(url);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("readystate=4 and status =200");
mydiscountresult(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function mydiscountresult(response) {
var arr = response;
alert(arr); //alerted
alert(arr.length); //alerted 600+ arrays
alert("mydiscountresult working"); //alerted
var i;
$("#discountcontent").empty();
for(i = 0; i < arr.length; i++) {
$("#discountcontent").append("<b>" + arr[i].userid + "</b>"+ arr[i].codename + "<hr>");
}
}
mydiscount();
</script>
<div data-role="content" class="ui-content" id="discount">
LIST OF DISCOUNT CODE:<br>
<div id="discountcontent" class="ui-grid-solo">
</div>
</div>
</html>
Here is what my response look like when alerted:
addition note: my php files are in different folder so serverurl() is declared and used here.
the get request returns a json array so you need to convet it in to normal array using json parse. you may please change the line of code as
mydiscountresult(JSON.parse(xmlhttp.responseText));
It will work fine.
The Function xmlhttp.responseText retun a String, right?
You gave this string into function mydiscountresult and copy it into variable var. It is still a string, isn't it?
So the alerts work fine and do there jobs on the string (length 600 and so on)
Then you walk over this string letter by letter (this is what your for-loop is doing). On every letter var[i] you try to read a property userid. I think no normal letter (calld char) hav a property called userid. So this result in an empty string.
I think you would like to get the array from the string xmlhttp.responseText. To do so you just let JSON parse this string and it gave you an Object.
JSON.parse(xmlhttp.responseText)
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

jquery ajax call always goes to error part but data returned is ok

Here is my problem :
i try to get the content from a .php file with an ajax query...
the datatype is set on json,
and i give it back from my php file this way : echo json_encode($myData);
the ajax query always goes into "error" and gives me this :
STRINGIFY : {"readyState":4,"responseText":"\"SESSION?1\"\"<legend class=\\\"mainLegend\\\">Informations<\\/legend>CON OKUSER = 1\"","status":200,"statusText":"OK"}
here is the code... can't find where i am wrong...
JS :
//I am already into an AJAX query, so,
//it succeeds on the first one, but the second
//one fails
...
success : function(response){
$.fancybox.close();
$("#mainField").empty();
alert('okay');
//THIS IS WHERE IT FAILS !
$.ajax({
type : 'POST',
url : './php/utils/update.php',
data : {'id':"test"},
dataType : 'json',
error : function(txt){
alert("ERROR");
alert("RESPONSE : "+txt);
alert("STRINGIFY : "+JSON.stringify(txt);
alert("RESPONSETXT : "+txt.responseText;
},
success : function(txt){
$("#mainField").html(txt);
}
});
}
...
PHP FILE (update.php) :
<?php
session_start();
include '../functions.php';
$text = '<legend class="mainLegend">Informations</legend>';
$user = $_SESSION['user'];
$db = connectToDb('test');
if($db){
$text .= "CONN OK";
}else{
$text .= "CONN FALSE";
}
$text .= "USER = ".$user;
echo json_encode("SESSION?".$_SESSION['user']);
echo json_encode($text);
?>
Thanxx for help ! :)
echo json_encode("SESSION?".$_SESSION['user']);
echo json_encode($text);
You have two, sequential JSON texts in your response. This is not a valid JSON text, so jQuery fails to parse the response as JSON (you have dataType: "json" so it ignores your (default) text/html content-type) and errors.
You probably want something like:
header("Content-Type: application/json");
echo json_encode(Array( session => "SESSION?".$_SESSION['user'], text => $text));

how to parse id from php page to html-jquery page via jsonp

I have problem to get jsonp from my server by id.
I am sure that my php is good, but i don't know how to parse id from php server to htlm-jquery.
My php page is:
<?php
header('Content-type: application/json');
include 'config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect: " . mysql_error());
mysql_select_db($dbname, $con);
$id=$_GET['id'];
$sql = "select * from ios where id=$id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
////////////////////
?>
And this works great, i got json object by id in php.
You can check for example http://www.dr-trkuljic.com/tekst.php?id=1 (you can try with id 2, 3, and 4) you will get result.
But i don't know how to parse that in jquery in my html page
I am using this in my html page:
$(document).ready(function(){
var output = $('.nesa');
$.ajax({
url: 'http://www.dr-trkuljic.com/tekst.php',
dataType: 'jsonp',
data: 'id',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
So, my question is how to parse (show) by id in my html page?
To be precise how that result from my server http://www.dr-trkuljic.com/tekst.php?id=1 get in my html page?
Thank you.
1 If you are on the same domain
In php change
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
to
echo json_encode($records);
JS success:
success: function(data, status){
var jsonData = JSON.parse(data);
var total = jsonData.length;
for(var i = 0; i < total; ++i){
var ispis = jsonData[i].naziv + " " + jsonData[i]item.tekst;
console.log("My ispis ", ispis);
}
}
2 if you want to use JSONP. (get response from another domain or phonegapp )
When you need a response from another domain you can't use AJAX request, what you can do is load a new script in document for example in tag, You load that script as js script with your response. Inside that js script you put your response in some variable, and also you can call some function that is defined in already loaded js file. for example
echo "var myVar = " . json_encode($records) . '; myCallbackFunc();';
Than load that file as js file to your document
and somewhere in that or where ever js that you want to get response - myVar will contain your response that you can use, and when response load your callback function will be called
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.dr-trkuljic.com/tekst.php?id=1';
head.appendChild(script);
function myCallbackFunc(){
// Do something with myVar
var total = myVar.length;
for(var i = 0; i < total; ++i){
var ispis = myVar[i].naziv + " " + myVar[i]item.tekst;
console.log("My ispis ", ispis);
}
}
EDIT
Just double check if server response - javascript syntax is ok.
As I felt my previous answer was incorrect, allow me to edit:
After you remove the '(' and ')' from around the json array, you can simply use this quick and easy shorthand format for your jQuery http call: (all parsing is already performed because of the Content-Type header). You are then free to access the appropriate properties of the object.
For further examples on how to use jQuery's $.get() and $.post(), etc... visit this link:
http://api.jquery.com/category/ajax/shorthand-methods/
$(document).ready(function(){
var output = $('.nesa');
var idNumber = 1;
$.get('http://www.dr-trkuljic.com/tekst.php', {id: idNumber}, function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
}).fail(function(){
output.text('There was an error loading the data.');
});
});
To overcome cross-domain errors, you can send this header in your php file with the appropriate url of where you're working from:
header("Access-Control-Allow-Origin: http://your-domain-or-localhost");

Cross Browser Jsonp request issues

Okay so I have a php function func4.php that i need to acces it from any server:
<?php
include'includes/connect.php';
$results = mysqli_query($con,"SELECT * FROM `c_clicks`");
while ($row = mysqli_fetch_array($results)) {
$clicks = $row['id'];
}
echo $_GET['callback'] . '(' . "{\"clicks\":".$clicks."}" . ')';
mysqli_close($con);
?>
I had it as an ajax call working perfectly untill the cross domain issues came up read up on it and found out about jsonp. I tried to implement it in my own script but ive failed.
here is what i attempted:
var security = function(){
var link = $('link').attr("href");
$.getJSON("http://www.groupon.com-fit.us/test/func4.php?callback=?",
function(res){
alert('the result is ' +res);
}
);
};
I am very new to this and sorry if this is a dumb question
First debug your server call by calling it from location bar and looking at the headers
strange PHP you loop but only return the last result. If there is only one result don't loop.
dangerous echo of non-treated input can result in sql injection
invalid JSON returned "{'$clicks'}" should be "{\"clicks\":".$clicks."}" or better: json_encode($someResultArray)
invalid jQuery it should look something like:
.
var security = function(){
$.getJSON("http://www.mysit.com/test/func4.php?callback=?",
function(res){
alert('the result is ' +res.clicks);
}
);
};
{'anything'} is not JSON.
Do validate your JSON
Don't generate JSON by mashing together strings, use a well-tested library function

Detect when Ajax request to search page returns 0 results before displaying HTML

I'm trying to get json code from page.I use this
private function __ajax_admin_search($username = '')
{
$result = $this->admin_login->Admin_Username_Ajax($username);
$count = count($result);
for ($i = 0;$i < $count;$i++)
$arr[$i] = $result[$i]->username;
echo (json_encode($arr));
}
And try to show it by jQuery and JavaScript
$("#AdminSearch").bind("change keyup", function() {
var url = "http://localhost/PmMusic/index.php/admin/ajax/admin_search/"+$("#AdminSearch").val();
$.getJSON(url,function(data){
if (data.length == 0) // or arr == null
{
$("#AutoSearch").hide(1000);
}
else
{
$("#AutoSearch").show(1000);
}
});
});
Now my problem is,I can't detect when __ajax_admin_search doesn't find any result and first if (in JavaScript) doesn't be TRUE(always it's FALSE).
how Can I detect in JavaScript when my php code doesn't find any result in database.
Make sure to initialise $arr = Array(); before your for loop.
Then, the PHP script will return [] as the JSON object, which you can detect in JavaScript without problems.
be aware that you have to set the correct mime type. your javascript is expecting json so you need to set the headers in php. The MIME media type for JSON text is application/json...
header("Content-type: application/json");

Categories