I was wondering if there is a solution to use a javascript function with PHP variables which i'm getting from a database. I know that PHP is a server language and javascript, a client language but i'm actually facing that problem. Maybe somebody can help me ?
I have points' GPS coordinates : "latitude" and "longitude" saved in my database and I get them by a function in PHP which returns me a PHP tab with th data in it.
Then I would like to insert the different points in a Google map with this javascript function :
function afficherPoint(latitude, longitude) {
var point = new google.maps.LatLng(latitude,longitude);
var optionsMarqueur = { position: point, map: map, title: "test" }
var marqueur = new google.maps.Marker(optionsMarqueur);
}
Thanks in advance
You can post the variables directly onto JavaScript (not the other way around), such as:
<?php
$name = "John";
?>
<script>alert("My name is <?php echo $name; ?>");</script>
Or if it's a dynamic thing, you can use AJAX.
If you are using jQuery, check this documentation: jQuery AJAX
You can call out to a PHP Script, and get new variables and do anything with them.
Just output the variable with PHP.
<?php
$myVar = 'I am a variable';
echo '<script>
var stuff = "'.$myVar.'"
</script>';
Then you can use the variable in javascript
You could render your javascript using PHP.
You could have php define global JS variables, and you can then access them using javascript in a seperate file,
You could have your javascript asyncronously load the data from your webserver
Yes, you can use php in javascript functions. A very basic example
var aVar = "<?php echo $aVar; ?>"
you can use ajax to this project :
This tutorial from google
you can try
https://developers.google.com/maps/articles/phpsqlinfo_v3
Related
I have some PHP code inside the script so I need
the JavaScript value as a PHP variable, as follows:
<script>
;
var js_var = 123;
var php_var = <?php js_var ?>;
alert(php_var);
;
</script>
Using jQuery to send the value to a PHP page will return the value but not as a PHP variable:
$.get("page.php", {js_var_name: js_var}, function(data) {alert(data)});
I tried also all jQuery AJAX functions: load(), post() and the ajax() method, none of them pass back the value of PHP as above requested.
Is it possible to implement the above with jQuery?
Likely you have a syntax issue with :
var php_var = <?php js_var ?>;
Unless you used define() your php variable should start with $ and you need to echo it so that it gets printed to the page
var php_var = <?php echo $js_var ?>;
If you are assuming that php will read the prior javascript js_var=123 it won't. Javscript is a client side language and php is server side.
You cannot simply mix PHP and JavaScript. The former is executed on the server, the latter on the client, namely in the user's browser. In order to hand a value from PHP to JavaScript you need to output JavaScript code via PHP or do a AJAX-Request to a PHP-Script, as you tried. When using AJAX, it is the easiest solutions to have PHP script that returns a JSON string. When calling this script using $.get() the result will be stored in a JavaScript variable and you can access all the values from there.
Take a moment and a deep breath...and then start thinking about your scopes again.
I have this code that executes a for loop in javascript with a php array inside of it. Is there anyway I can use the variable for the loop inside of the php variable for example. This is all inside of php.
echo '<script>
for (var i =0; i<4;i++){
alert("hey"'.$phparr[i].');
}</script>';
I know this will not work because the $phparr is a php variable while the i is a javascript variable is there anyway I can do this?
Try:
<script>
var phparr = <?php echo json_encode($phparr); ?>;
for (i in phparr){
alert("hey" + phparr[i]);
}
</script>
PHP is a server side language which means it executes before it reaches the client (browser).
JavaScript is a client side language which means it is executed in the browser (client side).
The best tool for a new web developer is Google search.
Learn how to search effectively.
You're almost there. In order to access the php array in javascript, you first have to echo out the php array into a javascript array. Try:
$phparr_imploded = implode(',',$phparr);
echo '
<script>
var arr = ['.$phparr_imploded.'];
for (var i =0; i<4;i++){
alert("hey"+arr[i]);
}
</script>
';
If your php array is coming from a database, or contains special characters that javascript may misinterpret, make sure to sanitize before outputting.
Are the objects in your php array strings? If so, you need to surround the objects with escaped quotations BEFORE the implode.
for($i=0; i<count($phparr); $i++){
$phparr[i] = '"'.$phparr[i].'"';
};
How about storing the PHP array in a Javascript variable and looping through as kpotehin suggests?
<script>
var i = 0, name;
var myArr = <?php echo json_encode($my_array); ?>;
while (name = myArr[i++]){
alert("hey " + name);
}
</script>
You should make it this way:
var arr = ["<?php echo implode('","',$array); ?>"];
for (var i =0; i<4;i++){
alert("hey"+ arr[i]);
}
Your basic problem is that you are forgetting that the PHP code and the JavaScript code do not execute at the same time. The PHP runs to completion, outputing HTML and JavaScript. Then the browser runs the JavaScript. If the JavaScript needs dynamic access to data in a PHP variable (including an array), then the PHP needs to generate JavaScript declaring the data in a JavaScript structure. That is what all the other answers are doing.
I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!
I have a javascript variable which holds some information and I want that to assign in a PHP variable. Here is what I am using:
<script type="text/javascript">
function redirectToFacebook()
{
var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script>
<?php
$_SESSION['sess_facebook_message'] = facebookMessage;
?>
Any help is really appriciable.
Thanks in advance
Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent.
However...
If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can.
For example...
JavaScript:
function something() {
// do something with somevar
somevar = 'content';
// make an AJAX request to setvar.php?value=content
}
PHP:
$_SESSION['somevar'] = $_GET['somevar'];
Make sure you take security issues of client-generated data into account, though.
If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either:
1) Load a new page with Javascript parameters encoded either as POST or GET
2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET
A simple example using a GET request (you simply append your parameters to the URL):
<script>
window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>
You probably want to assign this piece of code to a button or something...
what you are trying to achieve is not possible due to API limitation.It does not provide that.
may be you can try to redirect with javascript and pass variables form php to js. They way yout tru it, it can't work.
may be, im realy not shure
try this.
<?php
function redirectToFacebook() {
var facebookMessage = ?>
<script>
document.write(encodeURI(document.getElementById('txt_msg').value));
</script>
<?php
}
?>
or using cookies.
How do I call PHP variables or queries in JavaScript?
<script>
var foo = <?php echo $foo; ?>;
// or, if foo is a string;
var foo = '<?php echo addslashes($foo); ?>';
// for anything more complex, you'll need to use json_encode, if available in your version of PHP
var foo = <?php echo json_encode($foo); ?>;
</script>
Please note, you can only do this one way. Don't expect any changes you make in javascript to come through to PHP.
PHP and JavaScript cannot mix directly. You use PHP server-side to generate and send JavaScript to the client. the JavaScript executes client-side and can communicate with PHP code on the server only via AJAX calls. This can be simplified drastically through the use of an AJAX library like jQuery.
You have to keep in mind that your PHP code is evaluated on the server, while JavaScript (normally) runs in the browser. The evaluations happen in different times, at different places. Therefore you cannot call a JavaScript function (or variable) from PHP, simply because you cannot call a function that exists on another computer.
You may want to check if Ajax is an appropriate solution for your problem.
Generally, you can't. PHP is server-side and Javascript is client-side (processed by the browser).
The exception is to use AJAX, which allows you to access PHP pages, which should then execute the action needed.
You can use JSON for this purpose which serves well for sending a big array to Javascript from PHP. We need to echo JavaScript code in PHP script or we can use Ajax for this. But usually we may need to send a big array. So we can do like this
<script>
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
?>
var foo = echo json_encode($arr);
</script>
The json_encode function will handle all escaping and other issues. Bug also make sure json_encode is available in your PHP version.