How to dynamically copy array from php to javascript? [duplicate] - php

This question already has answers here:
PHP array to javascript array
(4 answers)
Closed 9 years ago.
I'm writing code in PHP and HTML for the server side coding of a GPS tracking system. The PHP code will access the coordinates of the GPS from a database. I've found HTML code to display those coordinates on a map(as a Polyline). In the database, a new tuple will be added almost every minute, so we cannot specify how many elements are in the array, before hand.
How do I dynamically copy an array from php to javascript?
this is the website with the code for drawing the polyline.

How do I dynamically copy an array from php to javascript?
You can’t “copy” it at all, because PHP and JavaScript are two completely different worlds.
What you can do is transfer it in text form – for example by encoding it as JSON in your PHP script, echo-ing it out as JS code (or request it from the server in a new HTTP request via JSONP/AJAX), and parse it back into a JavaScript object or array structure.

Give something like this a try:
<?php
$arr = array('cat', 'dog', 'mouse');
?>
<body>
<script>
var jsArr = <?php echo json_encode($arr); ?>;
console.log(jsArr);
</script>
</body>
Should output
["cat", "dog", "mouse"]
in console

Related

php variable inside js code [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I need a php variable inside js code.
Why this doens't work?
index.php
<?php
$h = 966;
?>
index.js
var b = <?php echo $h;?>;
Error:
Uncaught SyntaxError: Unexpected token <
You can't run php inside a JavaScript (.js) file.
Take a look at the question shared by Ed Cottrell in the comment on your post for more information, but basically, PHP is a server language, whereas JavaScript is a client one—when your computer loads index.js, it sees the php script, but has no idea what to do with it.
A straightforward solution (though not the best) would be to output a <script> tag containing your variable inside from your php file— and then access it from your JavaScript file.
When your browser requests the Js file, the web server typically simply sends it the file in the response without processing it like a php file. It doesn't know you have php code in it. It does the same (just sends it to the requesting browser) for images, text files, etc.
You can try doing that in your php view/template/script (I would wrap the output in single quotes). Something like:
<script>var b = '<?php echo $h;?>';</script>
You could also make a JavaScript file with a php extension: index.js.php, and include this instead of index.js. You'll need to set some headers in the top of that file to let the browser know it's getting JavaScript:
header("content-type: application/javascript");
There is some slightly more advanced stuff you can do as well: use an htaccess file to parse certain requests (like for that Js file) using php, or using an asynchronous request (Ajax) to pull the value of 'b' from the server, but it looks like your doing something a bit more simple.

How to use javascript to access php variable? [duplicate]

This question already has answers here:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?> [duplicate]
(6 answers)
Access PHP variable in JavaScript [duplicate]
(3 answers)
Closed 10 years ago.
How to use javascript to access php variable?
Does only one way to write code (like var a={?echo $variable})in javascript?
Recommend some books on php and javascipt(include projects)?I don't know how to use knowledge in projects?
Yes, you were correct.
Because PHP is executed before JavaScript, you can't change it later on, but you could do something like this:
<? $aVar = "whatever"; ?>
...
<script>
var aVar = "<? echo $aVar; ?>"; // note the quotes! (SO's highlighter renders this incorrectly, starting a PHP block inside quotes is valid and will be recognized.)
</script>
That will send this to the client:
<script>
var aVar = "whatever"; // note the quotes!
</script>
var a=<?php echo $variable; ?>
PHP runs in server and js in client side, so Iguess there is not other you can get it. OR you need to use AJAX
I don't see how can you do that in any other method. PHP is server side, while JS is executed on client's PC (not on the web server). Theoretically and practically it's not possible.

Set PHP variable value from a Javascript Variable value without refresh [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get javascript variable value in php
I am looking for help to set value of a php variable from javascript variable.
I tried these but nothing worked:
Try 1:
<script>
<?php $phpVar = ?> jVar;
</script>
Try2:
<?php $phpVar = echo "<script>document.write(jVar)</script>";
Failed too..
Please help.
Please help!
Actually php is server side scripting language (that runs at server) and javascript is basically client side programming language (which runs in the browser) so you can't set a php variable from javascript. Look at these tutorials php and javascript.
But using ajax (javascript) you can pass javascript variables to php and can use them in the to the php script. Here is ajax tutorial link.

passing variables from php to javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am trying to create a site where someone can create an "item" and the database will store an id and php generates a url for that id. So next time when the person comes back with that url it will remember the person's settings (variables). Now the problem is that in my site javascript need to know these variables.
So what is the best solution for this? passing the variables in the superglobal "GET" or maybe cookies? Or is there a better way to pass these variables to javascript?
just use php to print some dynamic javascript
<script>
var myVar = "<?php echo json_encode($_COOKIE['somevalue']);?>";
</script>
There are multiple methods for providing the data to the client, such as:
Echo the variables in your javascript, var userid = <?php echo
$userid; ?>
JSON'fy your variables and supply them to your javascript via AJAX/jQuery: $.getJSON(url, function(data){ var userid = data.userid; });
I typically utilize JSON as much as possible when trying to present server-side data to the client-side, as it helps to separate the different layers.

Parsing a Separate PHP Array in Javascript

So, as sort of an exercise in learning, I am trying to port a site I was working on for someone, written in PHP, MySQL and CSS, over to Ajax (Specifically, really, just adding Javascript so that the page is dynamic instead of needing to constantly reload).
Unfortunately, I have some scripts I'd like to keep as PHP (for instance, a script to update a database given an array of victims) because I need it to interact with a database, and this means that the array must stay as PHP (I think).
So, given this file,
<?php
$victims = array(
// Animals
"chickens",
"horses",
"cows",
// Supernatural
"werewolves",
"zombies",
"vampires",
"phantoms",
// Human
"U.S. Congressmen",
"performance artists",
// Inanimate, non-mechanical
"pieces of fencepost",
"barnhouses",
// Mechanical
"robots",
"cyborgs"
);
?>
is there a way to reach into that file using Javascript an extract a value?
Or, come to think of it, would it be better to store the list of victims as an XML file so both the PHP and Javascript can read it? Or even, how would I go about doing that?
Read up JSON and check out json_encode() for PHP5.
You can convert a PHP array into JSON, this is a string. Then print that string out into your page and use it with your Javascript
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
This is especially useful when returning data for an Ajax request
<script>
var jsonarray = <?php echo json_encode(array("status" => "success", "message" => "Something was completed OK")); ?>;
</script>

Categories