get a variable from javascript and use it in php [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want that when the user clicks an image a pop up window shows up asking the user to input a name, in this case I want to create a folder in a directory therefore the user has to input the name of the new folder to be created.
Now to create the pop up I need to use javascript and to create the folder I need to use PHP (server side). I am using the following code:
When the user clicks the image:
<div>
<a id="myLink" onclick="MyFunction();">
<img src="images/create_folder.png" width="60px" alt="create folder"/>
</a>
</div>
The code I am using to execute this operation:
<script>
function MyFunction(){
var foldername = prompt('Enter Folder Name');
<?php
$foldername = $_GET['foldername'];
mkdir('users_page/folders/', true);
?>
}
</script>
The pop up window I showing however when I click the ok button the folder is not being created.
Can any one please help.
Thanks!

It is a good pratice on understand how php code works with javascript. Be precisely, how server works with client.
First, create a new file called CreateFolder.php and put it on same directory of javascript file and write following code.
<?php
$foldername = $_POST['foldername'];
mkdir('users_page/folders/matthewborgcarr/'.$foldername, true);
echo 'the folder name is:' .$foldername; // add this line
?>
Then, on your javascript, remove all php code and add ajax function
<script>
function MyFunction(){
var foldername = prompt('Enter Folder Name');
$.ajax({
type: "POST",
url: 'CreateFolder.php',
data: {foldername: foldername},
success: function (dataCheck) {
alert(dataCheck); // foldername is returned on alert.
}
});
}
</script>

The PHP code runs before the page is loaded, this means it runs before the javascript. In order to execute PHP code by means of javascript you'll need to implement an AJAX request.

Check out my answer on this question: Using AJAX to return query results based on drop down box
It's an commented example on how to do Ajax requests with Jquery & PHP. You might find it helpful as a starting point.

Related

How to execute a PHP function inside of a Javascript function?

I made a two PHP functions for my project, these two functions responsible for fetching different product category for different "online shop".
Now, I am implementing the function that when employee adding a new product, the employee first select which online shop does the new product belongs to (via a select), then depends on the online shop, the second select menu should display the correct options.
so, the first select looks like this
< Select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
here I need help on how to execute /call /trigger the php function inside of method "loadNew_CCV_Category".
Inside of function "loadNew_CCV_Category", it will get the select value, and this value will be the parameters for the php function.
Please help :D, Thank you !!!!
You can try this way,
<?php
function square($num)
{
echo $num * $num;
}
?>
<select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
<option>Select</option>
<option>Test Php</option>
</select>
<script>
function loadNew_CCV_Category(){
var phpData = "<?php square(4) ?>"
alert(phpData);
}
</script>
The short answer
You can not. PHP is executed server-side and only the PHP-generated page is then delivered to the browser, where JS takes over and can continue reacting to input, but only with information it already has.
The more helpful answer
You can, however, either deliver the information for both cases to the browser and decide which one should be shown, or, which in most cases will be what you would rather do, make another call to the server from within your JS.
That means you would have an additional PHP script, which executes the function and generates the page content you want to insert.
You would then access that script file using JS and insert the generated contents into your page.
As for how to do that, maybe
this answer might help.
EDIT: Also refer to Avi's answer on that.
You cannot execute php inside javascript. because php is server side program and javascript is browser related.
If you want to write php then you can try this.
alert("<?php echo 'hello' ?>")
or
$.ajax({
url: 'yourphpfilepath.php',
success: function(respon) {
$('.result').html(respon);
}
});
your code will be like this.
<Select name="Select_CCV_Webshop[]" id="ccv-webshop" onchange='loadNew_CCV_Category()'>
<div id=wheretoshowresult> </div>
<script>
function loadNew_CCV_Category(){
$.ajax({
url: 'yourphpfilepath.php', //url for your php function or file
success: function(respon) {
$('#wheretoshowresult').html(respon);
}
});
}
</script>

javascript value to php [duplicate]

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).

inside javascript assigning javascript variable into php variable [duplicate]

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).

How to call PHP script from within JavaScript

I need help on how to call an external PHP script from within JavaScript.
See below for my example
INDEX.PHP
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>
SCRIPT.PHP
<?php
//script.php
//Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>
First things first: What are you asking is cannot be done in the way you think. When a page is requested, the server runs the php file, and after that it will send you the javascript/html/css page to you. So when you see the page the php script has already done. Javascript is running on your machine, so that's why you can handle with it user interactions.
But, if you send a post request to the script.php, sending the information you want, then you will be able to interact with a php file. To do this, you need jquery. Here is the script how you can do it in jquery:
$.ajax({
type: "POST",
url: "yoursite/script.php",
data: "name="+myName,
success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});
You can download jquery from here: http://jquery.com/download/
After you have downloaded, you have to link it to your index.php the jquery.js file, as a normal javascript file.
In your php file, you can access the name with $_POST["name"], and the information you want to send back, you have to actually print it.
Something like this:
if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}
You can simply write
phpResult = '<?php echo $sometext; ?>';
But,
the js script needs to be in a php file. you cannot use this in .js file obviously.
this will not evaluate any runtime variables on the client side. because the page will already contain vars rendered by the php script from the server.
I use this method all the time specially for rendering php arrays and objects as js objects/arrays.

Using javascript variable in PHP with ajax [duplicate]

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>";
?>

Categories