Core JavaScript

AJAX Self Post with Parameters Example

AJAX is a method for retrieving data from a server without refreshing the web page. Below, we have a simple POST example program to demonstrate how AJAX works when passing parameters. This files posts back to itself and returns a result based on whether or not a parameter is in the post request.

IMPORTANT: This file must be accessed via a web server. That is, it must be on a server or served by a web server on a local machine. For example, if the file is local the program could be run by entering http://localhost:8080/XoaxSelfPostParamsViaAjax.php into the address bar of your browser, if the site is set up to run on port 8080. See our video on how to install and use IIS, if you do not know how to set up a web server.

XoaxSelfPostParamsViaAjax.php

<?php
  // This branch is executed during the AJAX call
  if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['keyEnteredValue'])) {
    echo "<p>This was sent as a paramter: <b>".htmlspecialchars(trim($_POST['keyEnteredValue']))."</b></p>";
    echo "<p>So was this: <b>".htmlspecialchars(trim($_POST['keyExtra']))."</b></p>";
  } else { // This branch is executed initially.
$sClientCode = <<<CLIENT_CODE
<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's PHP: Send a Self Post with Parameters via AJAX</title>
  </head>
  <body>
    <h1>AJAX Self Post with Parameters</h1>
    <script>
		function MakePostWithParameters(sInputValue) {
		  var qRequest = new XMLHttpRequest();
		  qRequest.open("POST", "{$_SERVER['PHP_SELF']}", true);
		  // This is necessary for the post parameters.
		  qRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		  qRequest.onreadystatechange=function() {
			if (qRequest.readyState==4 && qRequest.status==200) {
			  document.getElementById("idXoaxDiv").innerHTML=qRequest.responseText;
			} else {
			  document.getElementById("idXoaxDiv").innerHTML="Error";
			}
		  }
		  qRequest.send('keyEnteredValue=' + sInputValue + '&keyExtra=AN EXTRA VALUE');
		}
    </script>
    <!-- The callback is called when a NEW value is ENTERED into the input element -->
    <!-- The 'value' is the string inside the element. The element is an object. So we can use 'this' -->
    <input type="test" value="Initial Value" onchange="MakePostWithParameters(this.value)">
    <div id="idXoaxDiv" style="background-color:#F0F0F0;margin-top:5px;"></div>
  </body>
</html>
CLIENT_CODE;
  echo $sClientCode;
}
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.