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
Related
I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a php file that generates a variable and I would like the variable to be put into a JavaScript function which is called by onclick on the main page. Is this possible to send from PHP to JavaScript?
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
Just write:
<script>
var my_variable_name = <?php echo(json_encode($php_string)); ?>;
</script>
Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>
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);
}
Using the HTML5 Geolocation API I've ended up with some variables in Javascript that I need to pass to PHP in order to continue. My code is below, how could it be achieved? I've tried things along the lines of $variable = <script>document.write(variable);</script>;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>test</title>
</head>
<body>
<script type="text/javascript">
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else {
document.write("Geolocation is required for this page.");
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function errorFunction(position) {
document.write("Error");
}
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$lat = //TAKE FROM JAVASCRIPT
$lng = //TAKE FROM JAVASCRIPT
$url = "http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$lat.'&lng='.$lng.'&username=demo";
$json = file_get_contents($url);
$data = json_decode($json, true);
$geonames = $data['geonames'][0];
$town = $geonames['name'];
echo "Displaying results near ".$town.". <a href=#>Not in ".$town."?</a>";
?>
</body>
</html>
EDIT: OK, I've done some homework and now I know I'm looking at an AJAX XMLHttpRequest to slick over the two. However, its syntax has slightly thrown me (not to mention the cross-browser issues). Can anyone give me a nudge in the right direction with this one?
Considering Javascript is interpreted by the client only after the server interprets the PHP, this is impossible.
Your only way to pass the Javascript data to PHP and then show the PHP results would be to send the data retrieved by the Javascript to the PHP via AJAX/XHR and then use Javascript to display the response from the PHP script.
To pass javascript variables to PHP you will have no choice but to request a new page, since PHP stops executing when a page is sent to the browser.
You can pass to it either via GET, POST or COOKIE. GET is the easiest way: http://domain.com/page?town=XYZ. All you need to do afterwards is store your town in a PHP session and redirect to the desired page using header('Location: http://domain.com/page')
Using an Ajax request will allow you to do that without resorting to sessions and page reloads.
You are mixing Server-side scripting along with browser-side scripting
$variable dissapears on the browser-side and so it will always hold "document.write(variable);" whatever the script inside there is written in.
You can however use AJAX to send the data back to php & process it there.
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()">