Reputation: 35
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;
}
?>
Upvotes: 0
Views: 32
Reputation: 3669
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;
?>
Upvotes: 1