I was wandering if it is possible to send a php object/array from a database into a javascript function through html?
Here is what I am trying to accomplish:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
function myfuntion(test)
{
console.log("What is first fruit: "+test[0]);
}
</script>
I get this error in my console:
Uncaught SyntaxError: Unexpected end of input
myfuntion([
What am I missing? Hoping for help and thanks in advance :-)
It is because string generated by json_encode contains double quotes and conflict with onclick="..."
Try to wrap it with htmlspecialchars
Send object
To avoid quotes collision just store your json as an object somewhere:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
var data = <?php echo json_encode($test) ?>;
function myfuntion()
{
console.log("What is first fruit: "+data[0]);
}
</script>
Or using an argument:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
<script type="text/javascript">
var data = <?php echo json_encode($test) ?>;
</script>
Send object
<script type="text/javascript">
function myfuntion(jsonObj)
{
console.log("What is first fruit: "+jsonObj[0]);
}
</script>
Instead of pass in function direct use $test array json in js like this.
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
function myfuntion()
{
var test = <?php echo json_encode($test); ?>;
for(var i=0; i<test.length; i++){
console.log("What is first fruit: "+test[i]);
}
}
</script>
If you pass in a tag then it passes a string instead of json.
Hope this is helpful to you.
You are missing parentheses for PHP code inside myfuntion.
Send object
You are doing correct only thing missing is, you need to surround passed argument in parentheses as below.
<a href="javascript:;"
onclick="myfuntion('<?php echo json_encode($test) ?>');">Send object</a>
Because your code will echo json encoded values/string in argument (and string must be inside single of double quotes) and function arguments must needs to be surrounded in parentheses. But if it is number then it will work but when you are dealing with objects and array you must need to enclose them in ''.
And in your js code just parse that argument to JSON using JSON.parse method.
Related
This question has been asked a few times, and the answer seems to be to use json_encode but this is not working as my string contains a few more things than quotes.
This is the PHP string:
<img src="test.jpg" :class="{ 'add-class': comment == 1, 'another-class': comment == 2 }" x-on:click="submit()">
The :class and x-on: are AlpineJS attributes in case you were wondering (check it out, it's really cool!).
This PHP string is dynamically generated and I would like to pass it to a javascript variable, shown here as jsVariable:
<script>
function test() {
return {
jsVariable: ,
anotherVariable: true,
}
}
</script>
Update
If I use jsVariable: <?php echo json_encode($php_variable); ?>, I get SyntaxError: Unexpected token '&' on that line.
If I use jsVariable: '<?php echo json_encode($php_variable); ?>', (added single quotes) then the variable is parsed as a string and not as HTML.
Use json_encode():
<script>
function test() {
return {
jsVariable: <?php echo json_encode($php_variable); ?>,
anotherVariable: true,
}
}
</script>
If you just use ASCII coding, you may give base64 encoding a try.
PHP encode the string into base64, and Javascript to decode, like this:
<script>
function test(){
var str = '<?php echo base64_encode($str);?>';
return {
jsVariable: atob(str),
anotherVariable: true
}
}
alert(test().jsVariable)
</script>
Hope this helps.
Here is the code that I have:
https://jsfiddle.net/a6kukf3n/
The PHP variable $weekParses contains the following data:
WK 14,WK 15,WK 16,WK 17,WK 18,WK 19,WK 20,WK 21,WK 22,WK 23,WK 24,WK 25,WK 26,WK 27,WK 28,WK 29,WK 30,WK 31,
However, when I add it to the var weekCases on Javascript and try to print it to the console or my charts.js file it returns null, 1, 2 ,3 ,4 etc
What am I doing wrong? How do I send my PHP variable to JS?
Please create a new array in php and assign the value to array
$data_week=array();
while ($weeks = mysqli_fetch_row($numRowsQuery))
{
$data_week[]=$weeks
}
After that please try
<script type="text/javascript">
//pass php variable to js for open cases pw
<?php $weekParse = $data_week; ?>
var weekCases = <?php echo json_encode($weekParse); ?>;
</script>
Prepare PHP variable inside the PHP code and not in script tag
so in your PHP code write
$weekParse = json_encode($weeks);
And your script
<script type="text/javascript">
//pass php variable to js for open cases pw
var weekCases = '<?php echo $weekParse; ?>';
</script>
Hope this helps you.
I have a php array:
$array = array(‘1234’=>”Acme Company”,
“4321”=>”CustomerX”,
”1056=>”CustomerY”,
”1058”=>”google”,
”1059”=>”Yahoo”,
”1060”=>”apple”);
I am attempting to create an autocomplete with this data. so step 1 is to iterate through in javascript.
var clients = '<?php echo json_encode($array);?>';
$.each(clients, function(i,el){
alert(i+","+el);
});
When i do this, I get the error:
Uncaught TypeError: Cannot use 'in' operator to search for '2847' in {“1234”:”Acme Company”,”4321”:”CustomerX,”1056”:”CustomerY”,”1058”:”google”,”1059”:”Yahoo”,”1060”:”Apple}
I can not figure out why. if i alert(clients), it looks like a good array..
Try it like this, you had error with passing php variable into your js var.
Now it`s iterating through all of the array elements.
<?php
$array = ['1234'=>'Acme Company',
'432'=>'CustomerX',
'1056'=>'Customer',
'1058'=>'google',
'1059'=>'Yahoo',
'106'=>'apple'];
$array = json_encode($array);
?>
<script type="text/javascript">
var clients = <?php echo $array; ?>;
console.log(clients);
$.each(clients, function(i,el){
alert(i+","+el);
});
</script>
Use clients = $.parseJSON(clients); before each ( and remove " ' from the numbers.
var client_parsed = JSON.parse(client);
and then use client_parsed
In chrome, I have the following problem. (I don't have the problem in firefox.)
Here is my code:
echo $name[0]; // outputs: apple
and I use in Javascript:
var name= <?php echo json_encode($name ); ?>;
document.write(name[0] + "<br>"); // outputs: a
I want the name[0] showing apple but not a. How can I fix it?
I've written what you've described here:
<?php
$name = ['apple', 'banana', 'pear'];
?>
<html>
<body>
<script type="text/javascript">
var array = <?php echo json_encode($name);?>;
document.write(array[0]+'<br>');
</script>
</body>
</html>
And appleis written in the document body as you wanted. Now this only happens if your array (variable $name) actually has an array with "apple" as the first element.
You might be getting the error you've described if $name contains "apple" (a string) , in which case PHP tries to acces the first letter in "apple".
I had an onclick event as below.
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
the function works fine with the name like Mary, Chris and etc.
However, if the student name contains a ', e.g. Cheng'li, the function won't work.
I need help to fix this. How can I make the function works by 'escaping' the quote mark in name?
Thanks.
You need to add a call to htmlentities around the data you wish to echo.
Not doing so exposes your code to XSS attacks.
use PHP function addslashes
<?php
$str = "Is your name O'reilly?";
// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
IN your case
<?php echo addslashes($student_name);?>
REFERENCE
http://www.php.net/addslashes
Note: If your code contain html tag than use htmlentities (Entoarox Answer)
you can either use escape()
<div onclick="display_function(escape('<?php echo $user_id;?>'),escape('<?php echo $student_id;?>'),escape('<?php echo $student_name;?>'))"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
That is because you are passing the values in function in single quotes. When name will have a single quote, this will cause error.
try double quotes like
<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>
Just add \ before ' to tell your script that it is a string. I hope it helps
<?php
$user_id = 1;
$student_id = 1;
$student_name = "Cheng\'li";
?>
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>
If you cannot put \ directly in String, you need to use [addslashes][1]
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+addslashes(student_name)); //<-- testing only. I have my own code here
}
</script>