javascriptphpjqueryajaxhttp-post-vars

AJAX POST - how to use a js variable in PHP


The first time the page loads, there will not be anything in the POST data array. After it runs I want to be able to use whatever variable I send in the POST data in the PHP code so I can query my database based on parameters sent. Do I need to reload the page somehow to do this?

PHP:

if(isset($_POST['boarder'])){
    $boarder = $_POST['boarder'];
    function boarderCheck($boarder){
        echo "<script type ='text/javascript'>alert('$boarder');</script>";
    }
    boarderCheck($boarder);
} else {
?>
  <script defer src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="map.js"></script>
<?
};
?>

JavaScript (map.js)

$.ajax({
  type: "POST",
  data: {boarder: 'test'},
  dataType: 'text',
  success: function(response) {
    console.log(response);
  }
})

Solution

  • No you don't need to reload the page, especially since you are utilizing an asynchronous request (the A in AJAX) to the same URL.

    See this phpfiddle demonstrating your example (with a couple modifications). Click the Run - F9 button and then click the button labeled Board to run the JavaScript (with the AJAX request). If you open the browser console, you should see the requests in the Network tab. The main one should be a GET request to a page like code_41096139.php (the numbers will likely change). Then when the AJAX request is made, there should be a POST request to that same page. Expand that request and you should see the Form data.

    inspecting requests in network tab of console

    The only modifications made, besides adding the button and click handler, were to add the output element:

    <div id="output"></div>
    

    and then in the success callback of the AJAX request, set the text of that element to the response (in addition to the call to console.log()):

     success: function(response) {
          $('#output').text('response: '+response);
          console.log(response);
     }