Core JavaScript

AJAX 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 a parameter. There are three files below which you can create with a text editor. These files are assumed to be in the same folder on the server.

IMPORTANT: These files must be accessed via a web server. That is, they must be on a server or served by a web server on a local machine. For example, if the files are local the program could be run by entering http://localhost:8080/XoaxGetWithParamAjax.html 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.

XoaxPostWithParamAjax.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript AJAX Post with a Parameter Example</title>
</head>
<body>
  <script type="text/javascript" src="XoaxPostWithParamAjax.js"></script>

  <div id="XoaxDiv"><p>Fill this with the result of POST with a parameter value on the
  XoaxPostWithParamAjax.php file.</p></div>

  <br />
  <form action="">
    Parameter Value: <input type="text" id="ParamValue">
  </form>
  <br />
  <button type="button" onclick="LoadXoaxAjaxFile(ParamValue.value)">Load
  XoaxPostWithParamAjax.php</button>
</body>
</html>

XoaxPostWithParamAjax.js

function LoadXoaxAjaxFile(sParamValue) {
  var qHttpReq;
  if (window.XMLHttpRequest) {
    qHttpReq=new XMLHttpRequest();
    qHttpReq.onreadystatechange=function(sParamValue) {
      if (qHttpReq.readyState==4) {
        if (qHttpReq.status==200) {
          document.getElementById("XoaxDiv").innerHTML=qHttpReq.responseText;
        } else {
          document.getElementById("XoaxDiv").innerHTML="Error";
        }
      }
    }
  }
  qHttpReq.open("POST","XoaxPostWithParamAjax.php", true);
  var sParams = "from_xoax="+sParamValue;
  // This must be set for a Post!
  qHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  qHttpReq.setRequestHeader("Content-length", sParams.length);
  qHttpReq.setRequestHeader("Connection", "close");
  // Send the parameter value
  qHttpReq.send(sParams);
}

XoaxPostWithParamAjax.php

<?php
  if (isset($_POST['from_xoax'])) {
    echo "This was posted from XoaX.net: ".Sanitize($_POST['from_xoax']);
  }
  function Sanitize($sString) {
    $sString = strip_tags($sString);
    $sString = htmlentities($sString);
    $sString = stripslashes($sString);
    return $sString;
  }
?>
 
 

Output

 
 

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