Ajax using POST

A very simple ajax call

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body>
  <p onclick="loadDoc()">Click</p>

  <p id="ajaxOutputHere"></p>
</body>
</html>

<script type="text/javascript">
// call the function immediately when the page is first loaded
//  document.addEventListener("DOMContentLoaded", function() {
//    loadDoc();
//  });

// function to deal with images uploads
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 &amp;&amp; this.status == 200) {
      document.getElementById("ajaxOutputHere").innerHTML = this.responseText;
    }

  };
  xhttp.open("POST", "processupload2.php", true);
  xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  xhttp.send("param1=james&amp;param2=froggatt");
}
</script>

processupload2.php

<?php
echo $_POST['param1']." ".$_POST['param2'];
?>

To call the above function immediately after page load we can use this event listener

//call the function immediately when the page is first loaded
  document.addEventListener("DOMContentLoaded", function() {
  loadDoc();
  });

Sending a variable to Ajax

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body>
  <p id="2" onclick="loadDoc(this.id)">Click</p>

  <p id="ajaxOutputHere"></p>
</body>
</html>


<script type="text/javascript">
//call the function immediately when the page is first loaded
  document.addEventListener("DOMContentLoaded", function() {
  loadDoc();
  });

// function to deal with images uploads
function loadDoc(id) {
  $id=id;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 &amp;&amp; this.status == 200) {
      document.getElementById("ajaxOutputHere").innerHTML = this.responseText;
    }

  };
  xhttp.open("POST", "processupload2.php", true);
  xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  xhttp.send("param1="+$id);
}
</script>

processupload2.php

<?php
echo $_POST['param1'];
?>

Leave a Reply