This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 6 years ago.
I have one php file where I have a number input field. I can grab the value of my input field with jQuery and store it in a javascript variable, but now I want to pass this javascript variable in to a php variable. How easily can I achieve it ?
<input id="custom_price" type="number" class="custom_price" name="custom_price" value="10" min="10" max="1000">
<script type="text/javascript">
jQuery("#custom_price").live("change", function () {
var user_amount = jQuery('#custom_price').val();
});
</script>
<?php $final_value = *How can I pass user_amount here* ?>
You can't. You need to send that variable to server using GET or POST method to save in a PHP variable.
PHP is confusing, because two (or three) different scopes are running within the same sourcecode file.
Your sample has plain PHP:
<?php $final_value = *How can I pass user_amount here* ?>
Plain HTML:
<input id="custom_price" type="number" class="custom_price" name="custom_price" value="10" min="10" max="1000">
<script type="text/javascript">
</script>
and plain JavaScript:
jQuery("#custom_price").live("change", function () {
var user_amount = jQuery('#custom_price').val();
});
HTML and JavaScript run on the client (web-browser) side while PHP runs on the server side.
One step back:
A HTTP access has two basic different steps**:
Client (Webbrowser) sends a request
Server sends a response
That's all, no more magic, nothing inbetween: One question, one answer. Further communication requires additional HTTP requests (and responses).
Whenever a browser sends a request to yourscript.php, that request is received, all arguments are parsed and your script is starting. All PHP code sections are processed and everything else plain unknown static data.
In the end, the static data plus the dynamic output from your script are send back to the browser as one package. End of communication.
Each HTML page may contain one (or more) forms which tell the browser that additional information (arguments) should be included in the next request:
<form action="myscript2.php">
<input type="hidden" name="foo" value="bar">
<input type="submit" name="button" value="Send request">
</form>
A click on the submit button creates a completely new request, adds the values of the fields named foo and button and sends (submits) everything to the server.
Again the target PHP script is running and could output something, but not on the previously delivered web page***.
** Some techniques are working more or less slightly different, like continuation requests or websockets, but they're way behind the scope of this question.
*** JavaScript/Ajax could be used to manipulate a web page without reloading it, but thats again just a request, response and Javascript source processing the response on client side.
When a user visits the site, the PHP code is executed on the server and then sent to to the user. Javascript, on the other hand, is sent to the user and then executed on that user's machine. In a basic definition, this illustrates the difference between 'front-end' and 'back-end' development.
That being said. You CAN use PHP to insert values into javascript code, as that can happen on the server and then be executed by the user's machine. However, you CANNOT pass a javascript value to a PHP variable (within the same script/page) because the PHP has already been executed on the server by the time it makes it to your web browser.
As was mentioned by others, the solution is to send the (javascript) data to a PHP script on your server via a network call. You could utilize jQuery.ajax() to do this in your javascript, then your PHP script will need to accept the data and do something with it.
Indeed , there is a way to embed Js Inside PHP code , but , is it applicable or not , this is another issue
see the following simple code :
<input id="custom_price" type="number" class="custom_price" name="custom_price" value="10" min="10" max="1000">
<?php $final_value ="<script type=\"text/javascript\">
var e = document.getElementById('custom_price').value;document.write(e); </script>";
echo $final_value; ?>
First remember php is run on server side and javascript is run in client side. So to pass the variable to the server/php you need to send it via http request. You could for example use ajax:
$.post('file.php', { 'varname': 'varvalue'});
Also you will need to capture the parameter on you server side:
#file.php
<?php
$value = $_POST["varname"];
?>
Related
I am selecting a payment method and making an AJAX call But I am not able to print the paymentOption parameter
I tried storing it in a cookie
if(paymentOption == "default_cod"){
processOrderWithCOD();
optionPayment = Cash;
}
document.cookie = "$payment_option = $this.optionPayment";
PHP:
<?php
$paymentOptionDisplay = $_COOKIE['payment_option'];
echo $paymentOptionDisplay ?>
I am just trying to print paymentOption but later on its value is changed so need to save it and print
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
$paymentOptionDisplay = $_COOKIE['payment_option'];
Cookies usually will not be available until the page is reloaded / refreshed, which is why you're not getting the value that you're expecting. You'd really have to do the payment calculation in PHP and store it in a $_SESSION if you're looking for it to persist like a cookie.
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 3 years ago.
First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable
<script type="text/javascript">
function scriptvariable()
{
var theContents = "the variable";
}
</script>
to a PHP variable
<?php
$phpvariable
?>
That function in the JavaScript executes when let's say I click on a button.
Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.
So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
I have a webpage which contains an array generated with JavaScript/jquery. On a button press, I want to run a PHP function, which updates a MySQL database with the JavaScript array.
I have a .php file with a PHP function that connects to the database and runs an UPDATE query, I want to use the array with that.
So I have home.php, which has the button:
<?php
include_once ('submit.php')
?>
<center><button id="submit" class="button1" >Submit<span></span></button></center>
and the array:
<script>
selectedItemsArray;
</script>
and I have submit.php, which has the sql UPDATE:
function submit(){
$sql = $dbh->prepare("UPDATE pending_trades SET item_list=:itemlist,");
$sql->bindParam(':itemlist', /*array taken from home.php*/);
$sql->execute();
}
I'll convert the array into a JSON before I put it into the database, but I need to know how to get access to the array with my submit.php file, and how to run the submit() function on the HTML button click.
There are multiple issues here. Most crucially, you seem to be confusing server-side and client-side scripting.
You are including submit.php in home.php, which declares a function submit() on the server-side. Your code never executed this function while on the server-side, and so the server-side output is empty,i.e. <?php include_once ('submit.php');?> evaluates to nothing. What the client-side receives is a HTML file with only the button, the function submit() is never passed to the browser.
Remember: server-side scripts are ALWAYS executed on the server and NEVER passed to the browser. That means you will never see anymore <?php and ?> when the file hits the browser - those PHP codes have long finished.
What you need to find out in order to accomplish what you intend:
Use client-side script (JavaScript) to listen to button clicks.
Use client-side script (JavaScript) to submit the form to server through AJAX.
Use server-side script (PHP) to read the data POST-ed, extract the data into an array.
In effect, you are asking three questions. And they are really straightforward; you can read up yourself.
What I'd do is to suggest an architecture for you:
home.php or home.html: contains the button, <link href="home.css"> and <script src="home.js">.
home.js: client-side script to listen for button click and submit AJAX to submit.php.
home.css: styles for the button and other elements in home.html/home.php.
submit.php: server-side script to check for POST variables and the SQL update operation.
Another issue: you are using a deprecated tag <center>. I'd advise you to remove it and layout the button using CSS instead.
use jquery AJAX.
<button id = "submit" class = "button1" > Submit <span></span></button>
your js code
$('#submit').click(function(){$.ajax({
method: "POST",
url: "submit.php",
data: itemlist,
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
and your php file. don't include file
$array = json_decode($_POST['itemlist'], true);
Remember your js array itemlist should be json format e.g.
$itemlist = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 3 years ago.
First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable
<script type="text/javascript">
function scriptvariable()
{
var theContents = "the variable";
}
</script>
to a PHP variable
<?php
$phpvariable
?>
That function in the JavaScript executes when let's say I click on a button.
Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.
So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
This question already has answers here:
Passing Javascript Variable to PHP using Ajax
(2 answers)
Closed 8 years ago.
I am thinking to use Speedof.me api to find out the user download speed accurately.I will use the value of the download speed to determine which video quality will be used to stream video to the user.
<html>
<head>
<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
</head>
<body>
<h2>SpeedOf.Me API Consumer - Sample Page</h2>
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speed = testResult.download;
}
</script>
<?php
//how can i use the speed variable here
}
?>
</body>
</html>
I am a begineer with javascript and i would like to use the javascript variable in the php as shown above without reloading the page.I know that javascript is executed client-side and php is server-side but from what i read online is that ajax is the way to go.Also is there a way in which i can store the result of speedof.me so that i don't need to run the test every time the same user view a video
Thanks for helping me out guys
you can make an ajax call to server to use the javascript variable in php
function onTestCompleted(testResult) {
var speed = testResult.download;
$.ajax({
url:"link to php script" // e.g test/index.php
type:"POST", //method to send data
dataType:"json", //expected data from server
data:{speed:speed}, //data to send server
success:function(data){
alert(data); //alert response data after ajax call success
}
});
}
on php script you can use that javascript variable speed after checking $_POST[]
echo $_POST['speed'];
passing PHP values to javascript can just be echoed. But javascript to PHP is a bit complicated.
Server scripts like PHP are executed first before Browser scripts (i.e. javascript) do their job. this means, after the page has loaded, your php won't do any good anymore, EXCEPT, you use Ajax requests.
what I use is jquery function .post() (if you're wondering why i use post, you can do your own reading about this functions including .ajax() and .get() )
PHP code somewhere found in /project/execute.php
$speed = $_POST["speed"];
echo $speed * 5;
and in your javascript...
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speedresult = testResult.download;
// here's the magic
$.post("/project/execute.php", {speed:speedresult}, function(result) {
alert(result);
} )
}
PS. DON'T FORGET TO IMPORT JQUERY IN YOUR SECTION OR THE BOTTOM MOST PART OF THE BODY
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
You do not seem to understand the fundamental differences between Clientside and Serverside Code.
The PHP Code will be executed serverside; only the output is sent to the browser. Then the browser executes the Javascript.
One solution to your problem would be to load the video dynamically with Javascript (either per Ajax or a simple video link naming convention). To store the speed test results, use a Cookie.
It doesn't work that way. As you said, JavaScript is client side. Your PHP page is processed by the server first--meaning, all PHP code gets executed first before any of your HTML, CSS, and JS. It doesn't matter if your JS is positioned first before PHP since PHP will get evaluated first. After that, it's sent back to the client for the browser to process HTML, CSS, and JS.
For your case, after running the speed test, send the value back to a PHP script via AJAX. You can use jQuery to make AJAX calls easier. Store a cookie using JS to indicate that the test has been executed once. You'll need to modify your JS so that it will check if this cookie is present and skip the speed test.
try this :-
<?php
echo "<script>alert(speed)</script>";
?>