How To Send Variables From Javascript To Php
Solution 1:
You probably have never learned the difference between javascript and php
Javascript is clientsided, which means everything is processed by your local system. PHP is server sided which means everything is processed by the server and parsed into html.
You can't send a value from javascript into plain php like you did. You can however send a post or get to the same script and let that reload a part of your script
Solution 2:
You're not the first to want this, and not the first to be told it is impossible the way you imagine. When you browse to a PHP page things go basically like this:
- Browser sends HTTP request to server
- Server determines what page to send to the browser
- Server discovers you want a PHP page
- Server executes PHP
- Server sends what is returned by PHP to the browser
- Browser doesn't know about the PHP and displays HTML
- Browser executes Javascript.
Now the important part is that the browser doesn't know what PHP is, but can execute JavaScript, while the server doesn't know what JavaScript is (for simplicity's sake) but can execute PHP. Bottomline: it is hard to communicate between the two because they are executed in different places. You'll most probably want to use AJAX, so here is a supersimple sample:
The PHP page we're going to fetch:
<?// We're on the server// We're going to output something:echo"Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).?>
JavaScript (with jQuery) to fetch the PHP page:
$("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).
Solution 3:
I suggest too, use AJAX or something to pass your javascript values to PHP. You can create a AJAX call, add the data from your javascript, and catch the data in your PHP file.
var value = "Jan";
$.ajax({
url: "/form.php",
type: "post",
data: "name=" + value
});
in your PHP file you can do:
<?php$catchedName = $_POST["name"];
?>
Post a Comment for "How To Send Variables From Javascript To Php"