AJAX with Javascript and PHP example

AJAX is called Asynchronous JavaScript and XML. Unlike a form, it will reload the entire page or bring you to another page to show you the result after you hit the submit. AJAX is a technique allows us to update parts of a web page without reloading the whole page. It exchanges the data from the front end web page with the server code and asynchronously updates a portion of the web page after it gets the data feed from the server.

The AJAX application we will be building here shows the factors of a number entered in the input box. The javascript code will pass the number entered in the input box to the backend PHP code, and the PHP code will return all the factors of this number. All these actions will happen within one page and without reloading the whole page. All we need are 3 files below for this AJAX application, one for html, one for javascript and one for php.

getFactors.html

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="getFactors.js"></script>
</head>
<body>
<form> 
Enter a positive number: <input type="text" onkeyup="showFactors(this.value)">
</form>
<p>Factors:<br> <span id="factors"></span></p>
</body>
</html>

getFactors.js

function showFactors(num)
{
if (num.length==0)
  { 
  document.getElementById("factors").innerHTML="";
  return;
  }
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("factors").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getFactors.php?q="+num,true);
xmlhttp.send();
}

getFactors.php

<?php
// get the parameter q from URL
$q=$_REQUEST["q"]; 
$factors=array();

if(ctype_digit($q))
{
    $n=intval($q);
    for ($x = 1; $x <= sqrt(abs($n)); $x++)
    {
        if ($n%$x == 0)
        {
            $factors[]=$x;
            $z = $n/$x; 
            if($z != $x)
              array_push($factors, $z);
        }
    }
    sort($factors);
}

echo empty($factors) ? "Please enter an integer!" : implode(",", $factors);

demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search