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.
Related
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.
The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....
I have the following code which throws the following error:
Uncaught SyntaxError: Unexpected identifier
I know its something simple, cant see it. Thank you in advance.
<?php $this->Html->scriptStart(array('block'=>'scriptBottom','inline' => false)); ?>
var phpRandom = "<?php echo json_encode($randomSponsor); ?>";
<?php $this->Html->scriptEnd();?>
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"]);
I am getting an "Uncaught SyntaxError: Unexpected token ILLEGAL" error when try to load a page with a php variable.
$(document).ready(function() {
$.get("index.html", {token:<?php echo $token; ?>}, function(data) {
//codes..
});
});
I can't seem to echo $token in my javascript and I am sure $token is valid.
Can someone help me solve this issue? Thanks a lot!
You're echoing text from PHP into a Javascript context, which means you have to generate valid Javascript code. Simplest solution: json_encode()
{token : <?php echo json_encode($token) ?>}
json_encode() will take care of any quoting/escaping which needs to be done.
e.g. if $token = 'foo', then you'd be producing
{token: foo}
and be producing an undefined variable error.
you need to put quotes around the php output otherwise it will be treated as a javascript variable rather than a string
{token:'<?php echo $token; ?>'}