I'm trying to pass a PHP variable to Javascript like this..
var url = <?php echo $urlArray[0]; ?>;
The contents of $urlArray[0] is a string from a json decoded array
"baby"
When I run the code I get the error..
Uncaught ReferenceError: baby is not defined
var url = "<?php echo $urlArray[0]; ?>";
you forgot the quotes.
If you need to export more complicated data structure, you may need json_encode. This might be helpful if exporting arrays and/or objects.
json_encode is your friend - use to wrap anything you're trying to pass to javascript.
http://php.net/manual/en/function.json-encode.php
var url = <?php echo json_encode($urlArray[0]); ?>;
Related
Whats the best way to do this?
I have this $_SESSION["sessionOpentok"] I need to set to this java script var var session_id
Security isn't an issue, its okay for the end user to be able to see this session id.
I have heard of AJAX calls, json encode, delimiters, php echo, php print.
None seems to work. echo and print do not work due to quote being in the session variable.
JSON encode encodes this the number to a null.
Any ideas. Thanks
In theory, just var session_id = <?php echo json_encode($_SESSION['sessionOpentok']); ?>; should do it.
However, you mayhave an encoding problem if you're getting null. Try:
var session_id = <?php echo json_encode(utf8_encode($_SESSION['sessionOpentok'])); ?>;
Escape the string before echoing it:
var session_id = '<?php echo addslashes($_SESSION["sessionOpentok"]) ?>';
This might not work depending on how you plan to use the session_id variable as the strings won't match.
In my php code, I have
<?php
$test = json_encode($array);//$array is a valid multidimensional array
?>
I am passing this variable to a javascript function and I am trying to set this variable to javascript.
<script>
var test = "<?php echo $test;?>";
</script>
(To clarify I am using codeigniter framework and for simplicity I did not use how I am sending the variable to the page)
But when I execute the above code, I am getting
Uncaught SyntaxError: Unexpected identifier
I have checked all my syntax.
Thank you in advance.
Don't put the decoded json array inside double quotes in the javascript. Change to this.
var test = <?php echo $test;?>;
It's not required to wrap the output of json_encode in quotes, otherwise it will be interpreted as a string. At which point you'll need to decode it within JavaScript.
Is it possible to fill jQuery variable by PHP???
I mean something like this:
<?php
$string_php = "50%";
?>
And with "$string" variable I want to fill jQuery:
var jquery_string = "$string_php";
$('.bar1').animate({'height':'jquery_string'},500);
The code above is only idea how I would like to be working
Yes but with php tags <?php ?> (so that php knows its code):
var jquery_string = "<?php echo $string_php;?>";
$('.bar1').animate({'height':jquery_string}, 500); // no quotes for variables
It is possible because PHP (server-side) runs before jQuery (client-side). The page first goes to server and server returns the response (php code is parsed there) to the browser.
Sure
var jquery_string = "<?php echo $string_php;?>";
Since PHP is processed first on the server and the result is then sent to the user's browser, this is easy, and often done.
The above code would result in:
var jquery_string = "50%";
You would, however want to modify your second line, removing the quotes from the variable so it was:
$('.bar1').animate({'height':jquery_string},500);
since keeping the quotes around jquery_string would make force it to be interpreted as a string whereas you want a variable.
The end result would be the equivalent of:
$('.bar1').animate({'height':'50%'},500);
For simple variables, just do as the users said.
F.ex. var jquery_string = "<?php echo $string_php;?>"; (taken from #Blaster's solution).
In other words:
The most simple solution is to output a php variable that we intend to use as string literal via echo anywhere we define the variable.
But: a correct approach would be that everytime we use a serverside variable as a Javascript string, it should be encoded, because the above solutions would fail when double quotes are present. Here json_encode may come handy.
var jquery_string = <?php echo json_encode($var); ?>;
Code example
We want Javascript alert the string "Hey", dude!
$string = "\"Hey\", dude!";
echo "alert(\"" . $string . "\");";
results in:
alert(""Hey", dude!"); <--- will give Javascript error
Instead:
echo "alert(" . json_encode($string) . ");";
results in:
alert("\"Hey\", dude!"); <---- correct JS code
i have this in JAVASCRIPT , a.php -
function gettemplate(realnam) {
alert(realnam)
}
i want to pass all the a[] array in func_a.php to the first file a.php.. to use the array there in javascript .
how i do that?
thanks a lot
EDIT--
ITS WORKS ! , if anyone need --
$a= json_encode($a);
echo "<SCRIPT LANGUAGE='javascript'> gettemplate('$a');</SCRIPT>\n";
:)
you can return (echo) in the func_a.php an json string http://de.php.net/manual/en/function.json-encode.php and parse it in javascript
echo json_encode($a);
You will need to serialize and parse the Array, as XMLHttpRequests only can contain XML or raw text. The format of choice is JSON, which is broadly supported, including PHP and JavaScript.
Serverside you will use json_encode. Don't forget to serve the JSON with a valid MIME type. You also should encode your error messages to be valid JSON.
Clientside, i.e. in the callback function, you will use JSON.parse on the xmlhttp.responseText.
You also will find lots of information about this on the web, you only need to search.
Read about JSON particulary json_encode. func_a.php must return something like this:
header('Content-type: application/json');
echo json_encode($a);
To get object in javascript use this:
var myResponseObject = JSON.parse(xmlhttp.responseText);
I am developing an application having more than thousands of values. I am trying to make a dynamic array in JavaScript. I'm using AJAX to get my values. So I have to create a string from PHP ,it should able to convert from string to array in JavaScript.
How can I make a string in PHP that can be converted to array in JavaScript?
You are looking for JSON and json_encode():
$string = json_encode($array);
The content of the string will be the array written in valid javascript.
Use JSON notation to create a string of values and then read it from JS. The simplest way to do this is something like that:
<script type="text/javascript">
var myPHPData = <?php echo json_encode($myData); ?>;
alert myPHPData; // now you have access to it in JS
</script>
if you dont intend to use json , you can do something of this kind..
you can create a string of this kind in php (separate it by any delimiter)
$arr = "1;2;3;4;5;6;7" ;
in javascript you can convert this to array using split function
//make an ajax call and get this string (say str)
arr = str.split(";");
split() returns an array
arr[0] is 1
arr[1] is 2
and so on !!