0

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; } ?> 
3
  • your PHP doesn't have return any response, just echo the number, after that handle the response in the $.post success block Commented May 28, 2018 at 3:21
  • I don't really need any return response, I want to use the variable in the php file, but it doesn't seem to be getting through Commented May 28, 2018 at 3:28
  • if thats the case, that should work just fine, just make sure the php is in the correct path, the easiest way to debug if works is to actually echo $_POST['vwWid'] in the PHP side, and then check you network tab using your browser, if its there echoed, it means the server side received it Commented May 28, 2018 at 3:30

1 Answer 1

1

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; ?> 
Sign up to request clarification or add additional context in comments.

3 Comments

I can get the variable to display in a div okay. I don't really want the 1200 value, it is only a fallback. But this is all that is being echo'd. The problem is with the $.post not getting through to the php file...
That is because you are including the page in your code. Ajax works by making a request to a php page server side, the server then sends the response back to the requesting page and displays the results.
This works and I am now using this (albeit, the condensed $.post version). Probably a better way of doing it anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.