Unable to parse JSON (xmlhttp) - javascript

I've gone through literally all of the other questions on this topic but I can't seem to find a fix for this relatively easy problem:
console.log(xmlhtpp.responseText) results in:
[{"id":"1","name":"Filosofie","image":"yin-yang.png","background_color":"no"},{"id":"2","name":"Politiek","image":"politics.png","background_color":"no"},{"id":"3","name":"Geschiedenis","image":"history.png","background_color":"no"},{"id":"4","name":"Vocabulaire","image":"vocabulary.png","background_color":"no"},{"id":"5","name":"Wetenschap","image":"science.png","background_color":"no"}]
The problem occurs when I try to parse the string to an object like so:
JSON.parse(xmlhttp.responseText);
Which results in the following error:
Uncaught SyntaxError: Unexpected end of input
The string originates from a PHP file:
$results = $db->query("SELECT * FROM library ORDER BY id", true);
$categories = array();
while ($row = mysqli_fetch_assoc($results)) {
$categories[] = $row;
}
echo json_encode($categories);
I need to loop trough the object eventually but I can't get past the parsing, any advice would be very much appreciated.

The default Content-Type from XAMPP is text/html, so your browser is trying to parse it like this..
Set the content-type yourself..
header('Content-Type: text/javascript');
echo json_encode(["foo", "bar"]);

Related

EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. header is set to text/event-stream

Hi I get This error in my console using sse
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
js code is :
if (typeof(EventSource) !== "undefined")
{
var source = new EventSource("../api/updateWellData.php?uid=<?php echo $node_id ?>");
source.onmessage = function(event) {
var response = JSON.parse(event.data);
document.getElementById("result").innerHTML = response.test;
// some code like the above line
};
}
else
{
// refresh the page every 30 secs
}
The PHP Code is :
header('Cache-Control: no-cache');
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/event-stream");
require_once("../resources/config.php");
if (isset($_GET['uid']))
{
$uid = $_GET['uid'];
while (1)
{
$query = Query("SELECT * FROM well_data_last WHERE well_detail_id = $uid");
$result = fetch_array($query);
echo json_encode($result);
ob_end_flush();
flush();
sleep(1);
}
}
This is my first time using sse I used the following documents : mozilla | w3schools
This error occurs when your PHP code outputs text in the wrong format.
This may be either a PHP error message (all of which are outputted as raw HTML), or some other text on the page which does not fit the text/event-stream format.
If the output of the PHP file does not match the format required by text/event-stream, it will fall back to using text/html. Javascript requires event streams use the text/event-stream content type so the JS console will show an error, but this is just a symptom of the actual problem - to fix the issue you need to fix your PHP.
In OP's case, the issue is with their echo statement. All data outputted to the stream must be proceeded by data:, and ended with a newline \n. The stream itself must end with another newline to indicate that no more data: messages follow.
To fix the error, OP should change
echo json_encode($result);
to
echo "data: " . json_encode($result) . "\n\n";
Another issue with OP's code is that there is no protection against SQL-injection in the database query. While this is irrelevant to the issue at hand, it is worth pointing out that prepared statements should be used instead.
I hade the same problem and the problem was a syntax error in the php file which showed an error message.

How to use JSON between PHP and javascript

I have made an application requesting data to a PHP and javascript receives the data and displays it.
At first I did it by getting the data separated by ',' and it works fine, but I want to do it with JSON and this is where I have the problem.
I receive the data and try to decode them but it gives me the following error:
Uncaught SyntaxError: Unexpected token <in JSON at position 0
     At JSON.parse (<anonymous>)
     At XMLHttpRequest.xmlhttp.onreadystatechange
In the received variable I have:
"<meta charset="utf-8"/>
↵ {"rastro":"entrada:inicio-inicio-comprobarPerfil-conectar-","mensaje":"si","usuario":"Invitado47","password":"","email":""} "
My code is:
PHP
$jsondata = array();
$jsondata["rastro"] = $rastro;
$jsondata["mensaje"] = $mensaje;
$jsondata["usuario"] = $usuario;
$jsondata["password"] = $password;
$jsondata["email"] = $email;
echo '' . json_encode($jsondata) . '';
javascript
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var contenidosRecibidos = JSON.parse(xmlhttp.responseText);
I have looked at google for many examples and it seems all very simple but there is no way it works.
Thank you for your help
I don't know if this is the best solution but this is what I use to use JSON in Javascript via PHP.
PHP:
<script>
var datavalue= <?php echo json_encode($answers) ?>;
</script>
The data is a JSON object. I also recommend to have a look at jQuery, which provides excellent ways to call PHP pages and have JSON as a result.
It looks like your PHP page is throwing some error/warning.
Try to print response like this.
echo json_encode($jsondata);
That might not be the cause for your proble. But I strongly suspect that your PHP page is throwing some warning.
And are you sure $password is not "Undefined" ?
Try
console.log(xmlhttp.responseText)
before parsing it. You'll get the warning/error.
Thank you. The problem was in the beginning of PHP, in the first line had:
<meta charset="utf-8"/>

data.php:1 Uncaught SyntaxError: Unexpected token :

I've that very simple code
<?php
header('Content-Type: application/json');
include 'config.php';
$query = mysql_query("SELECT str_data ,occasione FROM Evento");
$arraydata = array();
$arraynome = array();
while($row = mysql_fetch_assoc($query)){
$arraydata[] = date("m-d-Y", $row['str_data']);
$arraynome[] = $row['occasione'];
}
$datanome = array_combine($arraydata, $arraynome);
echo json_encode($datanome);
?>
but when i use the chrome console on that website
http://www.ldida.altervista.org/calendario/index2.html
it gives
data.php:1 Uncaught SyntaxError: Unexpected token :
why?
You are including data.php as type text/javascript.
Therefore your browser tries to parse it as javascript.
The output of data.php is:
{"04-20-2016":"Compleanno","05-14-2016":"Compleanno","05-03-2016":"Battesimo"}
This is no valid javascript, therefore the error. This is not a php error but a javascript parsing error.
Get rid of <script type="text/javascript" src="js/data.php"></script> from your HTML/source code.
You're calling it via jQuery - you don't need to include it in the page itself.
You're also including it as text/javascript, which it is not.

Possible to make a php string into XML and send to JavaScript?

I want to form a string in my php server code as xml, and then send it to javascript so that ajax.responseXML can navigate through it and do things with the data. I haven't been able to find exactly what I need to accomplish this and have tried a few different methods. Here's the most recent thing I've tried.
<?php
header("Content-type: text/xml");
$xmlstring = "<?xml version'1.0' encoding='UTF-8'>";
$xmlstring = $xmlstring . "<book name='$name' author='$author'>";
foreach($rankings as $entry)
{
$xmlstring = $xmlstring . "<rank>$entry</rank>";
}
echo $xmlstring;
?>
I know the data is getting there because if I echo it as a string and open it directly, the numbers I need are getting printed. I'm using Ajax.Request to open the php file with certain parameters, and when it reaches the onSuccess function, ajax.responseXML is null. This is my first time dealing with xml so I could be doing something stupid.
function that makes the call:
function findRankings(author, name)
{
new Ajax.Request("server_code.php",
{
method: "get",
paramters: {"type": "rank", "name": name, "author": author},
onSuccess: makeGraph,
onFailure: ajaxFailed
});
}
function makeGraph(ajax)
{
alert(ajax.responseXML); // testing that it made it
.....// do stuff with the response
}
EDIT: I added the header and made it echo just the string. I also added the ajax functions. I keep getting null though. :(
As Dustin said, you need to echo $xmlstring; instead and add header('Content-Type: text/xml');
But you also have a couple of errors in your XML declaration. You're missing a = and a ?:
$xmlstring = "<?xml version='1.0' encoding='UTF-8'?>";
I'd recommend using an XML validator in future.
You used simplexml_load_string, which converts your XML string to an object.
Just echo your $xmlstring
For clean coding you should insert header('Content-Type: text/xml'); as #Twisty mentioned.

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

Categories