This is all in the same script. I know the difference between ajax and serverside code. I have php interwoven in this javascript script as follows:
<script>
<?php
$json_string = json_encode(array("agent_table" => "<span style='float: left;'></span>"));
?>
var response = $.parseJSON('<?php echo $json_string; ?>');
</script>
But parseJson is complaining of an error. The error disappears when I remove the styling from the span.
The error is 'Unexpected identifier'. This is in Chrome.
You have ' characters in your data. These will continue to be represented as literal ' characters in the JSON.
You are embedding your JSON directly into a JavaScript string, and that string is delimited by ' characters. The first ' that appears as data in the JSON will terminate the JS string.
This is a general problem when embedding on data format in another. You are embedding JSON in JavaScript in HTML.
Your options:
Replace every instance of ' in the JSON with \' (so they mean "Apostrophe" instead of "End of JS string")
Treat the JSON as a JavaScript object literal instead of trying to munge it into a string which you run it through a JSON parser.
The latter option is the sane one (so long as your goal doesn't involve proving that PHP can generate valid JSON).
var response = <?php echo $json_string; ?>;
You don't need to worry about further escaping for inserting into the HTML because the only sequence you need to worry about (inside a script element) is </script> and PHP's json_encode will output <\/script> for that anyway.
May be it?
<script>
<?php
$json_string = json_encode(array(
"agent_table"=> '<span style="float: left;"></span>'
));
?>
var response = <?php echo $json_string;?>;
</script>
try it!!!
<script>
<?php
$json_string = json_encode(array('agent_table' => addslashes('<span style="float: left;"></span>')));
?>
var response = $.parseJSON('<?php echo $json_string; ?>');
Related
I am trying to insert items into a javascript array for the autocomplete function. I take the values that I need for the array from a database, so I grab them with PHP. Then I just push each item into the javascript array. However, it keeps telling me that I have an "unexpected token ILLEGAL" and it looks like it's pointing at the single "quote" character that gets inserted, then has a newline, then continues to the actual value.
My javascript/PHP
<script type="text/javascript">
$(function() {
var availableTags = [];
<?php
foreach ($modelList as &$model)
echo "availableTags.push('$model');" . "\n";
?>
$("#devicemod").autocomplete({
source: availableTags
});
});
</script>
Then the error message...
$(function() {
var availableTags = [];
availableTags.push('
***Uncaught SyntaxError: Unexpected token ILLEGAL***
ODEL: T]422P');availableTags.push('');availableTags.push('!');availableTags.push('!6.1/120{ MODEL: TM402P');availableTags.push('!A`$');availableTags.push('!DP1110 CREATED ON: JAN 29 2002');availableTags.push('!MODEL: TM402P');
It should turn out to be...
availableTags.push('ODEL:T]422P');
availableTags.push('');
etc...
Using json_encode() you can do this in a single (and safe) step:
<script type="text/javascript">
$(function() {
$("#devicemod").autocomplete({
source: <?php echo json_encode($modelList); ?>
});
});
</script>
The json_encode() function makes sure that the values are properly escaped according to the rules of JavaScript notation. This prevents nasty surprises when the values contain single quotes in this case.
If $modelList is not a true list (i.e. the keys are not numbered sequentially), you should apply array_values() first:
...
source: <?php echo json_encode(array_values($modelList)); ?>
...
This is a bad idea:
echo "availableTags.push('$model');" . "\n";
if $model contains ANY javascript metacharacters, particularly ', you'll introduce syntax errors and kill the entire <script> block. Never directly output arbitrary text into Javascript context - you're basically vulnerable to the JS equivalent of an SQL injection attack.
At bare minimum, you should be using json_encode() to guarantee that your text is syntactically valid for the context you're using it in:
echo 'availableTags.push(' . json_encode($model) . ");\n";
or better yet... why do all this pushing when youd could just generate an array automatically?
<?php
$data = array();
foreach ($modelList as $model) {
$data[] = $model;
}
?>
var availableTags = <?php echo json_encode($data); ?>;
i am assigning PHP var to my javascript var and sending to PHP file through
ajax-jQuery, but my php variable contains newline chars which
i have replaced with <br>
e.g. $values1 = 'abc<br>pqr<br>xyz'; $values2 = 'xyz<br>lmn';
javascript - var data = 'val1=<?php echo $values; ?>&val2=<?php echo $values2; ?>';
and then ajax script to post data to PHP file
but when i print this data on console it is giving me error- SyntaxError: unterminated string literal.
Can anyone help ?
Your JS code:
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Will give Javascript syntax error if one or more of your PHP variables $values1 OR $values2 contain single quote ' in them.
Make sure your PHP variable don't contain single quotes in them by replacing all single quotes to something else otherwise use double quotes " to create JS var like this:
var data = "val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>";
Provided PHP variables don't contain double quotes.
First of all, you have a typo, that might cause an error:
// --------------------------------v
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Then, I suggest you to use object as data parameter for Ajax request:
var data = {
val1: '<?php echo $values1; ?>',
val2: '<?php echo $values2; ?>'
};
Also it is better to escape single quotes ' in both $values1 and $values2 variables.
Try using <br /> instead of <br>. Just guessing here, no testing.
EDIT: SOLVED. Use any of the solutions below, but document.onload needs to be changed to window.onload. Also works without needing window.onload function anyway.
Here is the test.php file that i'm working with
<?php
include("conn.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script src="js/jquery.js"></script>
<script type="text/javascript">
document.onload = function (){
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
console.log(jsonObj);
alert( jsonObj.Auckland );
};
</script>
</body>
</html>
I have verified in Chrome Developer tools the value of jsonString to be
'{"Auckland":37616,"Wellington":35357,"Christchurch":29818}'
After that I don't get any log on the console or any alert box. I have also tried JSON.parse method instead of jQuery.parseJSON to no avail.
I'm trying to get this JSON into a datatable format used for google charts geo chart which looks like this bit of code
var data = google.visualization.arrayToDataTable([
['City', 'Population', 'Area'],
['Rome', 2761477, 1285.31],
['Milan', 1324110, 181.76],
['Naples', 959574, 117.27],
['Turin', 907563, 130.17],
['Palermo', 655875, 158.9],
['Genoa', 607906, 243.60],
['Bologna', 380181, 140.7],
['Florence', 371282, 102.41],
['Fiumicino', 67370, 213.44],
['Anzio', 52192, 43.43],
['Ciampino', 38262, 11]
]);
If you don't put it as a string it would be an object and you would not have to parse it
var jsonObj = <?php echo json_encode($rowarr); ?>;
instead of
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
It looks like document.onload doesn't fire/already fired? you should use window.onload or $(document).ready() instead.
Since you are actually inserting the JSON with a php echo right inside the script tag in the actual html page, it technically becomes an object literal. There is no need to go through the extra parsing step in JavaScript.
So in your case, the value you assign to jsonString is actually already an object.
You need to parse JSON only if it really is in the form of a string. So the actual script part sent to the browser should look like this:
var cities = {"Auckland":37616,"Wellington":35357,"Christchurch":29818};
console.log(cities);
alert( cities.Auckland );
You don't get the alert box because most likely your code throws a JavaScript error and simply stops executing after you try to parse the object.
I guess the handler function is never fired: There is no load event on the document object (see window.onload vs document.onload). You don't need to wait for that anyway, because you have nothing in the handler that interacts with the DOM - and you execute it in the bottom of your <body> tag (see Is the 'onload' necessary when the code is at the bottom?).
As JSON is a subset of JavaScript, you can directly output it into a script as a object literal:
var jsonObj = <?php echo json_encode($rowarr); ?>;
console.log(jsonObj);
alert( jsonObj.Auckland );
No need to parse it. Especially, when your JSON had contained an unescaped apostrohe, this would have broken your string literal.
I'm writing a php script that needs to load a 2D array into a js variable as json. First i make the array then use json_encode to turn it into a string. Then I run a small bit of js to get it accessable on the client side. Like so:
$sBaseData = Filters::$sFilterBaseTypeData;
$sBaseData = str_replace('\r',' ',$sBaseData);
$sBaseData = str_replace('\n',' ',$sBaseData);
$sBaseData = str_replace('\t',' ',$sBaseData);
echo <<<HTML
<script type="text/javascript">
var validation_data = JSON.parse('$sBaseData');
</script>
HTML;
Firefox complains about an unexpected character here:
var validation_data = JSON.parse('{"enumeration":{"js":"","msg":""},"date":{"js":" var parts = widget.value.split('-'); var d = new Date(parts[0],parts[1],parts[2]); PASS = (d.getDay()>=1); ","msg":"Invalid date. Please Enter a date in the format: YYYY-MM-DD"},"text":{"js":"","msg":"what did you do?"},"integer":{"js":"if (isNaN(widget.value)) { PASS = false; } else { intVal = parseInt(widget.value); PASS = (widget.value == intVal); } ","msg":"Please enter an integer value"},"decimal":{"js":"PASS = isNaN(widget.value); ","msg":"Please enter a number"},"group":{"js":"","msg":""},"dealer":{"js":"","msg":""}}')
I tried using http://jsonlint.com/ to find out which character was at fault but it says it's all valid and wonderful. I replaced some characters that were causing issues, is there anything else I should be replacing?
The problem is you have ' in your string while you are using ' to quote the string.
If your json string is valid, you don't need to parse it even. The below will work.
echo <<<HTML
<script type="text/javascript">
var validation_data = {$sBaseData};
</script>
HTML;
Uh...
var parts = widget.value.split('-');
Putting that in a string that uses single quotes will break it. Use a JSON encoder to output your JavaScript literal.
Your JSON is valid but in your js code the simple quote closes the parse function's argument.
Try like this:
"date":{"js":" var parts = widget.value.split(\'-\');
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to pass an array of strings from PHP to Javascript using $.ajax()?
I want to pass a associative array from php code to javascript code. Please help me. how do I do this ? Is JSON helpful in this matter? If yes then please provide a simple code for help. Thank you.
From comment below:
HTML + PHP code
<td>
<input type="text" style="width:70;" name="<?php echo $quantity;?>" id="<?php echo $quantity;?>" onkeyup="check_valid_range('<?php echo $itemName;?>','<?php echo $quantity;?>',<?php echo json_encode($product_inventory);?>);">
</td>
<script type="text/javascript">
function check_valid_range(product_field, quantity_field, inventory){
var product = document.getElementById(product_field).value;
var quantity = document.getElementById(quantity_field).value;
var v = inventory[product];
alert(v);
}
</script>
JSON is perfect:
<?php
$mySweetJSONString = json_encode($myAssocPHPArray);
?>
<script>
var iWantThePHPArrayHere = <?php echo $mySweetJSONString; ?>;
</script>
User pst brought up these concerns:
"array("</script>") -- darn, just broke this "perfect" approach."
It seems to work because (</script> => <\/script>): jsFiddle
"What about ]]> which could occur in XHTML?"The string is able to be transferred.jsFiddle
Update:
In regards to debugging the problem with the JS:
Are there any errors in the console? One of your document.getElementById(...) might be returning a null. Therefore the member value doesn't exist.
I always believed JSON were invented for this:
<script>
var myArray = <?=json_encode($myArray)?>;
</script>
This will render like this:
<script>
var myArray = {"key":"value","key2":"value2",...};
</script>
Safeness
This is perfectly safe for javascript, as JSON is a subset of the javascript syntax. This means that any JSON string can be treated as Javascript.
PHP's json_encode() is perfectly safe when embedding JSON in <script> tags too, because PHP escapes the / character:
json_encode('</script>');
=> "<\/script>"
So it's not possible to write </script>, which is the only way to escape a <script> tag. (Everything in a <script> tag is part of the script, it's not parsed as HTML.) JSON allows to escape the / for this purpose.
So no JSON string can escape a <script> tag.