简体   繁体   中英

jquery.post not passing data to php file

I am having trouble getting the jquery.post method to pass a variable to a php file. I can print the variable to a div using javascript okay but when I pass it to the php file it will only return the fallback value I have put in. Can you suggest why it might not be working?

<script type="text/javascript" src="../jquery.min.js"></script>

<script type="text/javascript">
function vwidth(){
    var vwWidth = window.innerWidth;
    document.getElementById('printVar').innerHTML = vwWidth; //test js variable - ok
    $.post( "listGen.php", {vwWid: vwWidth});
}
</script>

<body onLoad="vwidth()" onResize="vwidth()">
<div id="printVar">
</div>
<div>
<?php 
    include 'listGen.php';
    echo $viewwidth; 
?>
</div>

listGen.php -

<?php
    if (isset($_POST['vwWid'])){
        $viewwidth = $_POST['vwWid'];
        }
        else {
        $viewwidth = 1200;
        }
?>

Updated

Your JS Page:

<script type="text/javascript" src="../jquery.min.js"></script>

<script type="text/javascript">
function vwidth(){
    var vwWidth = window.innerWidth;
    document.getElementById('printVar').innerHTML = vwWidth; //test js variable - ok
    $.ajax({

      url: 'listGen.php',
      type: 'POST',
      data: {vwWid: vwWidth},
      success: function(data){
        console.log(data);
       $("#myDiv").text(data);
     }

   });

}
</script>

<body onLoad="vwidth()" onResize="vwidth()">
<div id="printVar">
</div>
<div id="myDiv">
</div>

Your PHP page:

<?php

 if (isset($_POST['vwWid'])){

 response =  $_POST['vwWid'];

 }else {

   response = 'You did not get vwWid in your post request.';

  }

echo $response;
?>

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