简体   繁体   中英

Transfer javascript variable to php on the same page without submitting

Hi I would like to transfer my javascript variable to php, it is just like a real time transferring. The user input, which is entered in a text box, will be transferred to php script to check if it is in the database. Then, the output will be displayed in another textbox that is readonly.

You will have to use AJAX for this. I hope it would be better if you can understand the difference between client-side(JavaScript) and server-side(PHP) script. There are a lot questions have been answered with the similar issues. Please google and you can find them with examples. Also refer Client side vs server side basics .

Difference Between Client Side & Server Side Programming

You'll need to look into AJAX. It sounds scary as an acronym, but it's quite easy to use.

In your Javascript (using jQuery, and assuming you have a textbox with the id "searchbox":

$.get("search.php", {"term":$("#searchbox")}, function(data) {
    alert(data);
}

In your PHP file "search.php":

echo "Yay! " . $_GET['term'] . " Woo!";

If you run the javascript on the textbox's keyup event, it'll get data live. So if you typed: "Hello World" into the box, you'd get a stream of annoying messageboxes saying:

"Yay! H Woo!", "Yay! He Woo!", "Yay! Hel Woo!", "Yay! Hell Woo!"... "Yay! Hello World Woo!"

From there it's a matter of making the PHP code return something useful. For that look into JSON. From there, it's a matter of writing Javascript to do something with the new, useful information.

http://jquery.com/

http://api.jquery.com/jQuery.get/

http://www.json.org/

http://en.wikipedia.org/wiki/Ajax_(programming)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM