export variable in JavaScript [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Access a JavaScript variable from PHP
I have one JS code that return my geolocation (latitude, longitude) and I would like to reuse these information in a PHP code. My webpage has .php extention and I have set global variable but it doesn't work.
How can I do that ?
<script type="text/javascript">
function getCoordPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
});
}
}
</script>
<?php
echo 'Latitude is $latitude';
?>

You can't just combine the two; Javascript executes in the browser, PHP on the server (before the page even reaches the browser). If you want to communicate a Javascript result to your server, your should submit it using a form, or use AJAX for asynchronous requests.

One of the methods are from $_GET method
var test1 = "myvalue";
var link = "thispage.php";
window.location = link+"?test1="+test1;
Then read the value from the testpage.php
Another methods is $.get, or $.post request to a php page.
$.post("mypage.php", {
myvar : "myvalue",
"myanothervar" : "myanothervalue"
}, function(data) {
//data contains the output from the script
});

I think the issue is that you are mixing client side code (javascript) with server side code (php). The php on the server cannot access the information from the client at run time since the client runtime doesn't exist yet. The client must submit it back to the server for use.
The php code executes and the response is sent to the client. Then the client page is executed from the top of the page to the bottom. At that point the server doesn't know what's going on on the client. You could load the client page and and then use jQuery to make a server side call (AJAX) back to php to pass it the information.
something like (I'm a bit rusty on jQuery)
$.get('myurl/sendgeolocation', { lat : lattitude, long : longitude }, function (data) {});
Then you would want the server do do whatever it needs to do in the function(data) callback to update the screen as necessary or whatever.

Your PHP code is processed first by the server and then sent to the viewer. Then the JavaScript code is executed, so PHP has no way to know what JavaScript is doing since it is processed prior to the JavaScript. You could use AJAX to pass the JavaScript information to a PHP script and then get something back from it, but it really depends on what you want to do with all this.

This is what exactly the answer you expect
//index.php
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function getCoordPosition()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
obj ={};
obj.latitude = position.coords.latitude;
obj.longitude= position.coords.longitude;
//latlngvalue = $.get('index.php',obj,"html");
$.ajax({
url:'fetch.php',
data:obj,
dataType:'html',
success:function(obj){
latlng = obj.split('-');
$('#latlng').html("Latitude : "+latlng[0]+"| Longitude :"+latlng[1]);
}
});
});
}
}
</script>
</head>
<body>
<div id="latlng"></div>
<button onclick="getCoordPosition()" >Get Geocode</button>
</body>
</html>
//fetch.php
<?php
if(isset($_GET['latitude']) && isset($_GET['longitude'])):
echo $_GET['latitude'].'-'.$_GET['longitude'];
endif;
?>

Related

How to call function from jquery to php?

PHP:
$product_code = $_GET['product_code'];
$countryCode = getCountryCode();
<script src="js/register_script.js" type="text/javascript"></script>
Jquery:
function getCountryCode() {
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
I want to get my country code from the jquery to perform some validation task, however, i wasn't able to retrieve the country code. Any idea what should i do for it to work? please note that the library is already been called. (I had read up on examples but dont really understand how it works..)
It is not possible to directly call PHP function from JavaScript and vice versa. Part of the reason for this is that as #Pekka indicated JS runs clientside (in your browser) while PHP runs server-side (on your server).
It is however possible to use AJAX for your purposes:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function getCountryCode()
{
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
function doAjax(){
var countryCode = getCountryCode();
$.ajax({
'url' : '<THE_URL_TO_YOUR_PHP>?countryCode=' + countryCode,
'method' : 'GET',
'success' : function(data){
console.log(data);
// do your handling here
},
'error' : function(data){
console.log(error);
// this function is executed on an HTTP error
}
});
}
</script>
PHP
This is your php file that would do your validation. In principle it is a different file than the file that outputs the html as shown above.
$countrycode = $_GET['countryCode'];
# handle countrycode
echo "<What you want to return to JS>";
Edit
On the additional question of how to get session variables to js.
Would I navigate to your page in my browser, the following would happen: If I requested a file with an .php extension, the PHP processer gets run on it. This processer identifies all code between the tags <?php and ?> as PHP, and thus runs all this code. If it encounters an echo statement, it echo's out the specific value at the location of the php-block.
After PHP is done processing, the page is served (given) to your browser, where it will be interpreted as a combination of HTML/javascript/... Javascript interprets everything between the tags <script> and </script> as javascript.
So, what if we where to make a request to index.php?par=val on your server, and index.php looks like
<script type="text/javascript">
function doStuff(){
var param = <?php echo json_encode($_GET['par']);?>;
}
</script>
(the json_encode function ensures that the variable is in proper json format. Of course you can change the `$_GET['par']; to be whatever you would like.)
Remember, PHP only cares about whats between the <?php and ?> tags, so this would output:
<script type="text/javascript">
function doStuff(){
var param = "val";
}
</script>
You will need to edit this to match your requirements of course, but this is the basics of passing parameters from PHP to client-side (JS)

using javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
i have this php and js code:
<script type="text/javascript">
function StartScript(script)
{
<?php require("StartScript.php"); ?>
}
</script>
Start
How can i get the "script" from the javascript function onto the end of the php file?
for example rather than:
<?php require("StartScript.php"); ?>
to have:
<?php require("StartScript.php?script=scriptname"); ?>
The full excerpt (provided that StartScript.php at the same level of current page, otherwise add absolute path):
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function StartScript(script) {
jQuery.getScript('StartScript.php?script=' + escape(script));
}
</script>
This will call StartScript.php with the parameter script. StartScript.php will generate the JavaScript code which will be executed in the client browser.
Reference: http://api.jquery.com/jQuery.getScript/
It's impossible to write server-side code (PHP) with a client-side code (Javascript). This will not work unless you use something like Ajax.
Maybe I misunderstood your question but this seems pretty easy...I would include all the js in the php file so the html side of things would have only....
<?
$script = "Page1";
include("StartScript.php");
?>
and the php would be...
<? if ($script == "Page1"){ ?>
function StartScript(script)
{
alert("IN");
}
</script>
<? } ?>
The problem is that you're mixing up the client (JS) and the server (PHP). PHP is executed on the server and produces some HTML which gets sent to the browser ("the client"). Browsers cannot run PHP because it's a server-side language.
You should evaluate what the desired interaction is between the client and the server here. For example, if you just need to execute some PHP to pass data to JavaScript, you can build up a JavaScript object:
<script type="text/javascript">
<?php // include script that gives you back some data, e.g.: ?>
<?php $somePhpData = array('red', 'yellow', 'blue'); ?>
<?php $jsonData = json_encode($somePhpData); ?>
var dataFromPhpScript = <?php echo $jsonData; ?>
// do something with the data
</script>
Otherwise, if you really need JavaScript to trigger a PHP script running, you're essentially doing AJAX. You'll likely want some sort of REST API. The idea is that you expose a URL from PHP that the JavaScript can call:
<script type="text/javascript">
jQuery(document).ready(function() {
function startScript(scriptName, success) {
$.get('/path/StartScript.php?script-name=' + scriptName)
.done(success)
.fail(fail);
}
startScript('name-of-php-script', function(data) {
// trigger some JavaScript that relies on the output of the PHP script
});
});
</script>

Passing javascript variable into php code without using GET parameters?

is there any way to get js variable in php, i try something funny like this:
<script>
var x = "random text";
alert("aaa<?php echo md5(;?>"+x+"<?php); ?>");
</script>
Of course it gives me error.
Parse error: parse error, expecting `')'' in X:XXX\index.php on line XXX
If there is a way without refreshing the page or using GET parameters, please let me know. Thanks
EDIT:
What I am trying to do is: hash(md5 inside php) the javascript variable.
PHP runs at the server, JavaScript runs at the client (browser). The only way you can pass a variable from JavaScript to PHP is sending it via an AJAX request.
There are several MD5 solutions out there for JavaScript, but it's not the same if you want the variable hashed before it reaches the user.
You can't do it like that because PHP builds the page before javascript is initialized. You'll have to do an AJAX request.
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var x = "random text"
$.post('md5.php', {md5:x}, function(data) {
alert(data);
});
</script>
<?php
echo md5($_POST['md5']);
?>
Or..
function md5(e){function k(h,i){var g=[h&2147483648,i&2147483648,h&1073741824,i&1073741824,(h&1073741823)+(i&1073741823)];if(g[2]&g[3])return g[4]^2147483648^g[0]^g[1];return g[2]|g[3]?g[4]&1073741824?g[4]^3221225472^g[0]^g[1]:g[4]^1073741824^g[0]^g[1]:g[4]^g[0]^g[1]}function n(h,i,g,j,s,m,o){h=k(h,k(k(i&g|~i&j,s),o));return k(h<<m|h>>>32-m,i)}function p(h,i,g,j,s,m,o){h=k(h,k(k(i&j|g&~j,s),o));return k(h<<m|h>>>32-m,i)}function q(h,i,g,j,s,m,o){h=k(h,k(k(i^g^j,s),o));return k(h<<m|h>>>32-m,i)}function r(h,i,g,j,s,m,o){h=k(h,k(k(g^(i|~j),s),o));return k(h<<m|h>>>32-m,i)}function t(h){var i="",g,j;for(j=0;j<=3;j++){g="0"+(h>>>j*8&255).toString(16);i+=g.substr(g.length-2,2)}return i}var f=[],v,w,x,y,a,b,c,d;e=function(h){var i=h.length,g=0,j=0,s="",m;for(m=0;m<i;m++){var o=h.charCodeAt(m),u=null;if(o<128)j++;else u=o>127&&o<2048?String.fromCharCode(o>>6|192,o&63|128):String.fromCharCode(o>>12|224,o>>6&63|128,o&63|128);if(u!==null){if(j>g)s+=h.substring(g,j);s+=u;g=j=m+1}}if(j>g)s+=h.substring(g,h.length);return s}(e);f=function(h){var i=h.length,g=i+8;g=((g-g%64)/64+1)*16;var j=Array(g-1);for(l=0;l<i;l++)j[(l-l%4)/4]|=h.charCodeAt(l)<<l%4*8;j[(l-l%4)/4]|=128<<l%4*8;j[g-2]=i<<3;j[g-1]=i>>>29;return j}(e);d=271733878;a=1732584193;b=4023233417;c=2562383102;for(e=0;e<f.length;e+=16){v=a;w=b;x=c;y=d;a=n(a,b,c,d,f[e+0],7,3614090360);d=n(d,a,b,c,f[e+1],12,3905402710);c=n(c,d,a,b,f[e+2],17,606105819);b=n(b,c,d,a,f[e+3],22,3250441966);a=n(a,b,c,d,f[e+4],7,4118548399);d=n(d,a,b,c,f[e+5],12,1200080426);c=n(c,d,a,b,f[e+6],17,2821735955);b=n(b,c,d,a,f[e+7],22,4249261313);a=n(a,b,c,d,f[e+8],7,1770035416);d=n(d,a,b,c,f[e+9],12,2336552879);c=n(c,d,a,b,f[e+10],17,4294925233);b=n(b,c,d,a,f[e+11],22,2304563134);a=n(a,b,c,d,f[e+12],7,1804603682);d=n(d,a,b,c,f[e+13],12,4254626195);c=n(c,d,a,b,f[e+14],17,2792965006);b=n(b,c,d,a,f[e+15],22,1236535329);a=p(a,b,c,d,f[e+1],5,4129170786);d=p(d,a,b,c,f[e+6],9,3225465664);c=p(c,d,a,b,f[e+11],14,643717713);b=p(b,c,d,a,f[e+0],20,3921069994);a=p(a,b,c,d,f[e+5],5,3593408605);d=p(d,a,b,c,f[e+10],9,38016083);c=p(c,d,a,b,f[e+15],14,3634488961);b=p(b,c,d,a,f[e+4],20,3889429448);a=p(a,b,c,d,f[e+9],5,568446438);d=p(d,a,b,c,f[e+14],9,3275163606);c=p(c,d,a,b,f[e+3],14,4107603335);b=p(b,c,d,a,f[e+8],20,1163531501);a=p(a,b,c,d,f[e+13],5,2850285829);d=p(d,a,b,c,f[e+2],9,4243563512);c=p(c,d,a,b,f[e+7],14,1735328473);b=p(b,c,d,a,f[e+12],20,2368359562);a=q(a,b,c,d,f[e+5],4,4294588738);d=q(d,a,b,c,f[e+8],11,2272392833);c=q(c,d,a,b,f[e+11],16,1839030562);b=q(b,c,d,a,f[e+14],23,4259657740);a=q(a,b,c,d,f[e+1],4,2763975236);d=q(d,a,b,c,f[e+4],11,1272893353);c=q(c,d,a,b,f[e+7],16,4139469664);b=q(b,c,d,a,f[e+10],23,3200236656);a=q(a,b,c,d,f[e+13],4,681279174);d=q(d,a,b,c,f[e+0],11,3936430074);c=q(c,d,a,b,f[e+3],16,3572445317);b=q(b,c,d,a,f[e+6],23,76029189);a=q(a,b,c,d,f[e+9],4,3654602809);d=q(d,a,b,c,f[e+12],11,3873151461);c=q(c,d,a,b,f[e+15],16,530742520);b=q(b,c,d,a,f[e+2],23,3299628645);a=r(a,b,c,d,f[e+0],6,4096336452);d=r(d,a,b,c,f[e+7],10,1126891415);c=r(c,d,a,b,f[e+14],15,2878612391);b=r(b,c,d,a,f[e+5],21,4237533241);a=r(a,b,c,d,f[e+12],6,1700485571);d=r(d,a,b,c,f[e+3],10,2399980690);c=r(c,d,a,b,f[e+10],15,4293915773);b=r(b,c,d,a,f[e+1],21,2240044497);a=r(a,b,c,d,f[e+8],6,1873313359);d=r(d,a,b,c,f[e+15],10,4264355552);c=r(c,d,a,b,f[e+6],15,2734768916);b=r(b,c,d,a,f[e+13],21,1309151649);a=r(a,b,c,d,f[e+4],6,4149444226);d=r(d,a,b,c,f[e+11],10,3174756917);c=r(c,d,a,b,f[e+2],15,718787259);b=r(b,c,d,a,f[e+9],21,3951481745);a=k(a,v);b=k(b,w);c=k(c,x);d=k(d,y)}return(t(a)+t(b)+t(c)+t(d)).toLowerCase()};
var x = "random text";
alert(md5(x));
You could use an ajax call to your server and have a webservice on the php side returning the information you need. Besides that? I don't think there is a way expect for refreshing.

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

How to pass data from Javascript to PHP and vice versa? [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax

Categories