I need to access a JavaScript variable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.
UPDATE: OK, I guess I simplified that too much. What I'm trying to do is create a form that will update a Twitter status when submitted. I've got the form working OK, but I want to also add geolocation data. Since I'm using Javascript (specifically, the Google Geolocation API) to get the location, how do I access that information with PHP when I'm submitting the form?
The short answer is you can't.
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
You're doing a $_GET, which is used to retrieve form values:
The built-in $_GET function is used to collect values in a form with method="get".
In other words, if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
If showing data to the user, do a redirect:
<script language="JavaScript">
var tester = "foobar";
document.location="http://www.host.org/myphp.php?test=" + tester;
</script>
or an iframe:
<script language="JavaScript">
var tester = "foobar";
document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>
If you don't need user output, create an iframe with width=0 and height=0.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!.
This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:
// -- index.php
<?php
if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">
var d = new Date();
var timezoneOffset = d.getTimezoneOffset() / 60;
// the cookie expired in 3 hours
d.setTime(d.getTime()+(3*60*60*1000));
var expires = "; expires="+d.toGMTString();
document.cookie = "timezone=" + timezoneOffset + expires + "; path=/";
document.location.href="index.php"
</script>
</html>
<?php
} else {
?>
<html>
<head>
<body>
<?php
if(isset($_COOKIE['timezone'])){
dump_var($_COOKIE['timezone']);
}
}
?>
JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
<script type="text/javascript">
function gotzpl(){
var query = window.location.search.substring(1);
if(query){
}else{
var timez = Intl.DateTimeFormat().resolvedOptions().timeZone;
if(timez != 'undefined'){
window.location = "https://sks.com/searches.php?tzi="+timez;
}
}
}
</script>
<?php
// now retrieve value from URL and use it in PHP;
// This way you can get script value in PHP
$istzg = $_GET['tzi'];
?>
<body onload="gotzpl()">
Related
Preapring for a Facebook competition while I have spare time, the Publish function with facebook has a once posted javascript function that you can define.
What I am looking to do is call a function to write a value unto a php form which will then be posted and submitting data into a database. I have tested to the extent that I know the idea is sound just calling a basic alert, I am just not sure how to get from calling the function to writing the value into the form.
This value I need to be able to call on in the page that the data is being posted to, to base an "if function" off, basically if "True/Yes" then I need it to process another php script in addition to the data its posting to the database
What I have now is:
<script type="text/javascript">
function isShared()
{
alert("Yes");
}
</script>
<input class="fieldbox" name='shared' type='hidden' value="value of 'display_alert()'"/>
I know it cannot be an alert, but this is pretty much where my current javascript skills leave me stranded.
<script type="text/javascript">
function isShared()
{
document.getElementById('xshared').value = 'Yes';
}
</script>
<input class="fieldbox" id="xshared" name="shared" type="hidden" value="" />
This will add the value Yes To the hidden field once isShared is called.
Are you looking to have the form automatically posted without the user clicking anything but the share button? The only reason I ask is that it sounds like what you are looking for is AJAX, to post data to the database silently without the need of the user to navigate away from their current page.
I'm still not 100% clear on what you're asking, but are you just looking to emit a server-side PHP variable into client-side JavaScript code? Something like this?:
<?php
// some code, etc.
$myVariable = "foo"; // some value
// more code, etc.
?>
<script type="text/javascript">
var myVariable = '<?php echo $myVariable; ?>';
// more JavaScript code, etc.
</script>
This would emit to the page as:
<script type="text/javascript">
var myVariable = 'foo';
// more JavaScript code, etc.
</script>
Basically anywhere that you need the literal value from the PHP variable, you'd write:
<?php echo $myVariable; ?>
I am not clear how exactly you are aiming to post the form data but you can set the input value using jquery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
$('#input1').val($('#input1').val() + 'more text');
<input id="input1" class="fieldbox" name='shared' type='hidden' value=""/>
Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission.
function showHint(str)
{
document.getElementById('TK').innerHTML = str;
var str = str
}
</script>
<html>
<head>Inputbox</head>
<title>TEST PAGE </TITLE>
<body>
<input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/>
<?php
$str = var str ;
echo "<a href = 'newpage.php?S=$str'/>" ; ?>
</body>
</html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" >
function process(){
var field1 = 'whatever';
var field2 = 'more whatever';
$.post("go.php",{field:field1,bext_field:field2},function(result){
alert(result);
});
};
</script>
This will alert out whatever you ECHO from GO.PHP.
You will also need a handler like:
onClick="process();"
on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following:
PHP executes before the user has a chance to see the page.
JS let you control what happens after.
Therefore, your problem is that you are trying to use PHP to do something it simply cannot.
Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS.
Think about it like this:
/*
assumes you already have an <a> on the page. if not, you'll
have to create a new <a> element dynamically. (google "mdn createElement"
for help)
*/
function showHint (str) {
document.getElementById('TK').innerHTML = str;
var link = document.getElementById('your-a-link');
link.setAttribute('href', 'newpage.php?S=' + str);
}
How do I use POST using jQuery/Javascript to send to another page and redirect to that page?
Sending variables using GET...
In Javascript
window.location = 'receivepage.php?variable='+testVariable;
When it is receive by PHP...
$var = $_GET['variable'];
How do I do that ^ , using $_POST?
I already tried...
$.post(
'receivepage.php', {
i: i
}, function(){
window.location = 'receivepage.php';
}
);
but it seems to lose the variable when it reaches PHP
Doing $.post is trying to post the information via ajax, and THEN redirecting to your page, so when you finally get there, the attribute "i" won't be received.
You could do someothing like this:
HTML
<form method="post" target="receivepage.php" id="myform">
<input type="hidden" name="i" value="blah" />
</form>
JS
<script type="text/javascript">
$("#myform").submit();
</script>
Does that solve your problem?
Edit
If your value comes from JS, you can add it like this:
JS
<script type="text/javascript">
$('#myform input[name="i"]').val(i);
$("#myform").submit();
</script>
According to your example, "i" is defined on the window scope, making it global and accessible from this script.
In your post example, $_POST['i'], would be your variable.
I have a PHP page with where I also use jQuery UI functionality. User drags Item from left panel into a box on the right. After it is dropped a dialog appears. If user clicks the first button he/she is redirected to a URL. I need to be able to change URL based on a user.
I can get the URL into a var or $_SESSION but I can't figure out how do I change it inside my JS function?
Here's the DEMO (drop item into box to get dialog).
UPDATE:
Below are all valid suggestions, however, my problem is that I have most of JS functions in external JS file (dragdrop-client.js).
I have added new var to my main PHP file
var endURL = "http://google.com";
but how do make my function checkLaunchpad() use it?
There are a number of different ways to do it, but often it is as simple as:
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
Where $url is the url you want them to go to (perhaps '/boxes.php?uid='.$_SESSION['id'];?)
That will translate to:
<script type="text/javascript">var myURL = 'http://whatever.and.stuff'</script>
EDIT
You just asked how you would have a function declared on an external JS page use the variable.
Well, fortunately, JS doesn't care when you declare the variable, so long as it has some value before you use it. And, if it doesn't have a value then, it will supply undefined;. This means you can declare functions which rely on global variables which won't exist for another three or for seconds/minutes/years/eons/whatever.
Additionally, the earlier a script tag is on a page, the earlier it will be evaluated -- a variable declared in the first tag will exist when the second js file loads.
So, if you want to have the above work as expected you have two options.
You could define the variable as the first script tag in the body of the page (thus, it is defined before checkLaunchpad is.
<script type="text/javascript">var myURL = '<?php echo $url; ?>'</script>
<script type="text/javascript" src="path/to/js"></script>
Or, if checkLaunchpad isn't called until after the body has loaded, you can place the definition anywhere in a script tag!
Find below code to redirect users to new page
<script type="text/javascript">
var endURL = "http://google.com";
function checkLaunchpad(url) {
location.href=url;
return false;
}
</script>
Test
for more reference check http://snook.ca/archives/javascript/global_variable
I would say store the url in a hidden field like:
<input id="hidUrl" type="hidden" value="<?php echo $url ?>"/>
And then change your javascript so it uses the value:
window.location = $("#hidUrl").val();
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