简体   繁体   中英

JS variable to PHP variable without buttons or refresh

I've searched for over an hour and tried many examples but none do what I need. From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm . I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh.

I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. The JS is only run once upon entering the site. But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm ).

The best way is to store the value you want for citynm into a session variable as below:

$_SESSION['citynm'] = $citynm

You have to do this either at page load, or by ajax. Then, you can use $_SESSION['citynm'] in any pages you want since its global.

USECASE 1: via user input

in your html document:

<input type="text" name="citynm" id="citynm" value="Brussels">

inside your javascript file (using jquery here for readability):

(function(){

    $('#citynm').on('blur',function(){
    // when the input value has changed, post its value to server.
var citynm = $(this).val();
        $.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){

// if the request is successful, the following script will be executed.
alert("server said: "+data);
        });
    });
})(jQuery);

And inside the file.php file:

<?php
    session_start();
    if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
      $_SESSION['citynm'] = $_POST['citynm'];
    }
echo "citynm is ".  $_SESSION['citynm'];

?>

USECASE 2: no userinput

   var cityname = city.short_name; 
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }

    (function(){

                $.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){

        // if the request is successful, the following script will be executed.
        alert("server said: "+data);
                });
        })(jQuery);

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