Is there a way to pass javascript value to php?
if(echo '<script>window.location.href="/mysite"</script>' === "/mysite"){
$myVal = 1;
}else{
$myVal = 2;
}
This way seems doesn't work
Nope you can't do it. If you want something like that best and easiest way is using JQuery ajax function http://api.jquery.com/jQuery.ajax/ which will send request to server with data you want to given script (easiest way - make other .php file?) and if you want something returned, it will be in ajax returned data. Read provided link and you should be good to go.
If you want to know on which site you are currently (as in example) you can use $_SERVER array and get variable which you want from it. List is here: http://php.net/manual/en/reserved.variables.server.php
PHP code executes server-side. JavaScript executes client-side. There's no way for the two to communicate unless you create a web service in PHP that is called from the JavaScript. Unfortunately that won't solve your problem.
If you're trying to set values based on the requested url, you could try:
if($_SERVER['REQUEST_URL'] === "/mysite"){
$myVal = 1;
} else {
$myVal = 2;
}
The code I see in your post shows that you completely misunderstand PHP and Javascript nature.
Send JS var through AJAX request and then work with it in some server-side script.
php is executed on the server side first.
then javascript is executed on the client side. So it's after the php has been rendered.
The only way to send javascript values to php, is using ajax to send an asynchronous call.
Related
I know PHP runs first but is there a way to get PHP to wait on an ajax request and then run its script? I have a php script here that I want to run but I NEED a variable from my JS file in order for it to run successfully. So was wondering if it's possible?
What I have is a normal request in my JS:
var myvar = data;
$.get('phpscript.php', {myvar: myvar} );
And in PHP:
$myphp = $_GET['myvar'];
But if i echo $myphp it returns "undefined", if I alert it however It displays the value; which means the php script is running before it even gets the request from ajax. Any way I could make the PHP wait?
Thanks.
Put the PHP that requires a variable in its own script and call it from the ajax call, once the ajax call gets a response update the DOM as needed.
PHP runs on server, then javascript runs on client to make the ajax call, then PHP runs on server returning data, then the javascript gets the data and does something with it.
$.get('phpscript.php', {myvar: myvar}, function(data) {
$('.result').html(data);
});
Inside the php file have something like:
$myphp = $_GET['myvar'];
echo $myphp;
The short answer is, no, you can't make PHP wait. PHP only runs on the server-side, by the time the AJAX request is sent, by definition, the page is already been sent to the client.
You'll probably have to do some refactoring. If the variable absolutely needs to be used for a PHP function, then you may need to move that logic into 'phpscript.php' or (less optimally) you may need to issue another AJAX request when you get the response from the first.
But my guess is that more commonly, you'll probably just have to figure out how to do what you want with javascript. If all you want is something equivalent to a PHP echo, you'll want to use Javascript (or JQuery) DOM manipulation for that.
EDIT: I forgot to mention, the other option is simply to do all the PHP stuff on the server-side before you send the page at all, instead of AJAX you'd want to do something in PHP like including your other php script and calling methods from it. But, everything you do on the server-side, the user is sitting there looking at a blank screen waiting for the page to load. So this isn't an option for anything that's not very quick.
I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.
I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.
I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.
I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.