my php code looks like this:
$result['firstName']['lastName']='johan';
echo json_encode($result);
how should i type to use this array in javascript with jquery?
...function(data) {
alert(data.firstName.lastName);
});
or
...function(data) {
alert(data.firstName['lastName']);
});
JQuery doesn't effect object access, so you can just do
data.firstName.lastName
Javascript doesn't technically have associative arrays, so technically in Javascript you're working with an Object. Either syntax you used should work.
The object['property'] syntax is only needed in javascript for numbers or syntactically ambiguous keys (e.g. those containing spaces).
This worked for me but its very ugly
<?php
$result['firstName']['lastName']='johan';
$data = json_encode($result);
?>
<html>
<body onload='myfunction(<?php echo $data; ?>);'>
<script>
function myfunction(data)
{
alert(data.firstName.lastName);
}
</script>
</body>
</html>
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'm doing something which I need to pass an array from my php to a function on an external javascript. I'm currently doing some test right now which looks like this:
<input type="text" onclick="show_error_message('<?php echo $array_sample ?>')" readonly="readonly">
and the javascript function is this one:
function show_error_message(test) {
alert(test)
}
my $array_sample contains data which is array("1","2","3"); but the return alert would be Array and whenever I change the $array_sample into $array_sample[0] when passing the parameters I got a data which is 1 as alert. I wonder how can I pass the whole array on this to be fetched also by an array in javascript. Well as you can see, I intended it to be a popup message for error handling which is why I need it to be dynamic.
Use json_encode
onclick='show_error_message(<?php echo json_encode($array_sample) ?>)'
or
onclick="show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)"
Notice the lack of quotes(') around the php code, this way an array literal is passed to show_error_message and not a string.
Encode PHP array to json data using json_encode() function.
And in Javascript use JSON.parse() to parse the Json string.
The below code shows how to pass php array to javascript:
<script type="text/javascript">
function mufunc(a)
{
var temp = new Array();
temp = a.split('~');
for(i=0;i<temp.length;i++)
{
alert(temp[i]);
}
}
</script>
<?php
$a = array('a','b','c');
$b = implode("~",$a);
?>
Click Here
is it possible to achive similiar results in JavaScript ? My aim is to not write static html within string literals.
<?php
if (someCondition) {
?>
I'm here, because PHP allows it.
<?php
}
?>
For example:
<script>
if (someCondition) {
</script>
I'm here, because JavaScript allows it.
<script>
}
</script>
I am aware of the following solution:
<p id = "variable">I'm here, because JavaScript allows it.</p>
<script>
var p = document.getElementById('variable');
if (!someCondition) {
p.parentNode.removeChild(p);
}
</script>
Nice thought, but it's not possible in the way you want it.
Every <script> element is evaluated as a JavaScript independent program, which will throw a syntax error in your case.
You'll have to generate the <p> element inside of your JavaScript.
i have array in php, and i need work with this array in jQuery.
What best way send array( or variable ) from php to jQuery?
Thanks
json_encode() (PHP >= 5.2) is arguably the easiest way.
$array_js = json_encode($array);
echo "<script type='text/javascript'> my_array = ".$array_js."; </script>";
If you don’t have to dynamically load it, try something like this:
<script>
var the_array = <?php echo json_encode($array); ?>
</script>
I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script.
for eg:
<?
$divtohide = "adiv";
?>
<script language="javascript">
function hidediv($divtohide) {
................
}
</script>
Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal:
function hidediv(divtohide) {
// Your code may differ here, mine's just for example
document.getElementById(divtohide).style.display = 'none';
}
And print out the PHP variable only when you're calling it, within a pair of quotes:
hidediv("<?php echo addslashes($divtohide); ?>");
addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break.
as BoltClock wrote, use php to pass the variable.
but you can do it by most simple way, just write hidediv("<?=$divtohide?>")
<script type="text/javascript">
function hidediv() {
divobj = document.getElementById('<?= $divtohide ?>');
divobj.style.display = 'none';
}
</script>