简体   繁体   中英

php is not sending data to javascript

I honesty did every possible search, watched lots of tutorials, but still cant make it work. The mistake is somewhere in connetion between javascript and php. The strange point is that connection is successfull and script works if I click the submit button when the page is in a process of reloading.

Please, help.

I call two variables, $l1 and $l2 from the php require-once which do some work on the page, then I use them in Java script to send to PHPfile onclick of submit button;

Button:

<input class ="button vote" type = "submit" onClick= "javascript: somefunction();" value = "do it" />

Function:

function somefunction(){

var hr = new XMLHttpRequest();

var url = "index.php";
var wn = "<?php echo $l1 ?>";
var ls = "<?php echo $l2 ?>";
var vars = "wn="+wn+"&ls="+ls;
hr.open("POST", url, true);

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.onreadystatechange = function() {
   if(hr.readyState == 4 && hr.status == 200) {
   var return_data = hr.responseText;
  document.getElementById("status").innerHTML = return_data;
   }
    }

    hr.send(vars); // execute the request
    document.getElementById("status").innerHTML = "processing...";
}

php acceptor on the same page:

<?php if (isset ($_POST ["wn"])){
$wnn = $_POST['wn'];
$lss = $_POST['ls'];...

try this:

var wn = document.getElementById("wn").value;
var ls =  document.getElementById("ls").value;

I presume you ar calculating these either diectly, or from a $_SESSION variable perhaps? When you view the source on the completed page check if the variables are present, perhaps just after you assigne the variables within php.

<?PHP
    if (isset($l1) && !empty($l1)) {
        echo "L1 is $l1";
    } else {
        echo "L1 wasnt set"; 
    } 
?>

then make sure the value up top matches that you're seeing in your javascript

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