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); ?>;
Related
I have a routine in my controller that retrieves the values from a single database column and builds a quoted array out of them:
$suppliers=$this->Model->find('list',array('fields'=>array('Model.supplier', 'Model.supplier')));
$strSuppliers="'".implode("','", $suppliers)."'";
$this->set('suppliers', $strSuppliers);
$strSuppliers is then fed to a jQuery script that creates an auto-complete dropdown list in the "suppliers" field in my Edit view:
<script>
$(function() {
var availableTags = [<?php echo $suppliers ?>];
$( "#MsrSupplier" ).autocomplete({
source: availableTags
});
});
</script>
The output of the variable is something like 'Tom', 'Dick', 'Harry', etc.
This works fine, unless any of the retrieved values contain single quotes. 'Tom's', 'Dick', 'Harry' breaks the array, and I'm having difficulty understanding how to escape the single quotes so that my dropdown will continue to function when they're present. I've tried changing the delimiter and swapping single quotes for double quotes, like so:
$strSuppliers='"'.implode("','", $suppliers).'"';
But that didn't work. What else might I try here?
Check out json_encode() for PHP to output a JSON string, and then look at JSON.parse() for use in your jQuery.
Instead of using implode() to generate your string, use json_encode() and then have JSON.parse() decode that for use in whatever application you need.
Edit: Added some code for clarity:
$strSuppliers = json_encode($suppliers);
and then in your jQuery:
var jsonStr = '<?php echo $suppliers; ?>';
var availableTags = JSON.parse(jsonStr);
EDIT 2: As ndm pointed out in the comments, you can do this more cleanly by directly assigning the Javascript variable to the output of json_encode():
var availableTags = <?php echo $suppliers; ?>;
I have an SQL database (I know for sure it includes remote access, if that's necessary to access a database through php). It definitely has at least one record in it, and I need to get each record and create a corresponding button that links to a php file, taking the first field for that record as a/n argument, variable, parameter, or whatever you call the whatever.php?variable=value.
For some reason, this code just gives me a blank page. Why?
<?php
$connection=mysqli_connect("myhost","myusername","mypassword","mydatabase");
$result=mysqli_query($connection, "SELECT * FROM myTable");
$resultArray=array();
while ($row = mysqli_fetch_array($result)) {
array_push($resultArray, $row['ID']);
}
$resultArrayImplode = implode(",", $resultArray);
?>
<script>
var resultArray = <?php echo $resultArrayImplode; ?>
arrayEntries = new Array();
arrayEntries = resultArray.split(",");
function CreateButtons(element, index, array) {
var button = document.createElement("input");
button.type = "button";
button.value = element;
button.onclick = function() {
document.location.href = "ButtonClicked.php?id=" + element;
}
document.body.appendChild(button);
}
arrayEntries.forEach(CreateButtons);
</script>
Thanks!
Your javascript assignment to resultArray is probably not syntactically correct due to quote characters, etc. Luckily, PHP's JSON functions automagically create good javascript for you.
Try this for the javascript output:
var arrayEntries = <?php echo json_encode($resultArray)?>;
Your problem is $resultArrayImplode; is a string, so
var resultArray = <?php echo $resultArrayImplode; ?>
renders as:
var resultArray = 1,2,3,4,5
Which is a syntax error.
What you can do is use JSON. JSON syntax is JavaScript syntax, so all you need to do is:
var arrayEntries = <?php echo json_encode($resultArray); ?>;
This should render as something like:
var arrayEntries = [1,2,3,4,5];
Which is perfect JavaScript syntax. Then the rest of your code should work.
I just don't see why do you need to use javascript for this, cant you just do the following :
<?PHP
foreach($resultArray as $result)
{
?>
Im a button click me</div>
<?PHP
}
?>
in my opinion, i see no real need for you to use javascript for this.
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; ?>');
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(\'-\');
I got really confused when i tried to transfer variables from php to js.
everything is fine when i try to get value using an id
for example:
var name = $("#name").val();
but my question is, if i want to convert for example this variable:
$id = 182938; //the id of the user
to this variable:
var id;
this question might be dumb... maybe easy for you, but not for me :p
I have looked it up and only found something like this anywhere i looked for:
<?php
$number = rand();
?>
<script language="javascript">
var num = <?php echo $number ?>
</script>
Does it have the same affect as passing down the value?
Thanks!!
Not quite. Encoding as JSON will ensure that it is a valid JavaScript literal.
var num = <?php echo json_encode($number) ?>
what the code does is:
<?php
$number = rand(); //assign random number to $number. let's say it's "3"
?>
//then these are printed on the page normally
<script language="javascript">
var num = <?php echo $number ?> //the $number is echoed at this position
</script>
and then the browser receives:
<script language="javascript">
var num = 3;
</script>
You have to generate syntactically VALID javascript. PHP can echo text into ANY part of the page it's generating, but that doesn't necessarily mean it's actually USABLE text. In your case, you've forgotten a ;, so your generated javascript is actually a syntax error:
var num = <?php echo $number ?>;
^--- missing
The same sort of thing occurs when you're outputting text. Consider where you're storing someone's name into a variable:
<?php
$name = "Miles O'Brien"; // <-- note the single quote
?>
<script>
var name = <? php echo $name ?>;
</script>
This LOOKS ok, but it'll actually generate yet another syntax error:
var name = Miles O'Brien;
there's no quotes around the whole string, and the embedded quote will START a string in javascript, leading the JS interpreter to complain about an undefined variable "Miles", an undfined variable "O", and an unterminated string literal.
Instead, the PHP should have been:
var name = <? echo json_encode($name) ?>;
The JSON encapsulation guarantees that you're embedding syntactically valid Javascript values.