from php to jquery - php

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>

Related

Return an Array in PHP and Javascript AJAX

Section 1
I'm trying to return an Array from PHP (after having created the file using fwrite)
I include that file on my next .load method (inside a Div) the new PHP file contains an include 'somefile.php'; there is my array ... and I would simply try to collect from PHP and use it the array with JS....
I once saw something like this ...
$(function(){
alert('<?php for_each($array as $key => $value){
echo $value; // Just an example
}
?>')
});
I wrote this piece of code on the fly so there might be a few sytax errors;
This works fine using PHP inside JS ...
I'm not sure if I heard PHP loads first and then JS ? or was it the other way around ?
Section 2
How about using JS inside PHP ?
for example ....
<?php
echo "var myArray = New Array();"
echo "myArray = ('Apple','Banana','Orange','Kiwis');"
echo "return myArray";
?>
and then being able to fetch the data strait with JS ?
<script type="text/javascript">
for(i=0;i<myArray.length;i++){
alert(myArray[i]);
</script>
So how easy can I manipulate both languages in regards to RETURNING the array for example so it could be used in the global scope?
PHP runs first, so you can use it to write JavaScript code, that will get run once the page has been processed by the browser.
This would build JavaScript code with an array from PHP:
<script>
var myArray = <?php echo json_encode(array('apple', 'orange', 'kiwi'); ?>;
myArray.forEach(alert)
</script>
The other way around, passing data from JavaScript to PHP, can only be accomplished with some form of AJAX.
using PHP in JS : In short, you can echo the values in JS codes, e.g.
window.location = '<?php echo $url; ?>';
using JS in PHP : You can use AJAX . post the values to a PHP script
The PHP runs on the server, so from Javascript's point-of-view (running in the client's browser) it's like the PHP was never even there.
You can easily pass the PHP array to Javascript using PHP's json_encode() function:
$yourPHPArray = array("blah","blah","blah");
echo "var theArray=" . json_encode($yourPHPArray) . ";";
echo "for(var i=0;i<theArray.length;i++)";
echo "{";
echo " window.alert(theArray[i]);";
echo "}";

Concatenate with php and javascript

i have to concatenate =>descriptif [i]= "'.$description[i].'";
in the loop for with this (i=0 ; i<16 ; i++):
<?php echo
'<script> var descriptif = new Array ();
</script>';
?>
i need this php array, to create a jquery function. Help me ...
Look into JSON functions for PHP, specifically json_encode()

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

Pass PHP variables to Javascript/jquery [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So far I know two ways to pass php variables to javascript.
One is by using
<script>
$(document).ready(function()
phpvalue=$("#hiddeninput").val()
})
</script>
<input type="hidden" id="hiddeninput" value="phpvalue">
And the other one is by having for example a button and using onclick
<script>
function clickf(phpvalue) {
}
</script>
<input type="submit" onclick="clickf(<?php echo phpvalue ?>)">
All of them work great but:
Is there any other way that I'm missing?
Which one is the "best"?
Any chance that I can use inside the script or the external js ?
<script>
$(document).ready(function()
var phpvalue = <?php echo $var; ?>
});
</script>
Like others already answered, just put a PHP tag whereever you would place the JS value, like var foo = <?= $php_value ?>; or var foo = <?php echo $php_value ?>;.
If you want to use this in an external JavaScript file, you have to make sure .js files get parsed by PHP. If this is not an option for you (for example, your host doesn't allow it), I suggest you set the values in a <script> tag inside your <head> and then just reference thos variables from your external JavaScript. In that case, I would strongly suggest you namespace them like var app_vars = { foo: <?= $bar ?> } in order to not clutter the global object.
Another way would be to retreive the values via Ajax. But the viability of this approach depends on your use case.
And another hint: if you want to pass multiple variables or arrays, there's JSON baked into PHP since version 5.2:
<?php
$my_complex_var = array(
'array' => array('foo', 'bar'),
'val2' => 'hello world'
);
?>
<script>
var my_complex_js_var = <?= json_encode($my_complex_var) ?>
</script>
<script>
var javascript_variable = <?php echo $php_variable; ?>;
</script>
Instead of assigning values to hidden inputs, you could just generate JavaScript directly:
$script = <<<EOT
<script>
var phpvalue = $phpvalue;
</script>
EOT;
echo $script;
for the top example you do not need to use val you could use any attr you like.
For example
phpvalue="myvalue"
then within jquery
$("#hiddeninput").attr("phpvalue");

use php array in javascript?

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>

Categories