AJAX with jQuery and PHP example

The ajax application we will be creating is for determining if a number is a prime number. There will be an input text box for getting a number and a input button for triggering the javascript function. This function will use the jQuery to call the server side php code to determine if the input number is a prime number and display the result to the page without reloading the whole page.

isPrime.html

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="isPrime.js"></script>
</head>
<body>
<form> 
Enter an integer: <input id="inputNum" type="text" ><input type="button" value="Is Prime?" onclick='isPrime()'/>
</form>
<div id="isPrime"></div>
</body>
</html>

isPrime.js

function isPrime()
{
  var num = $("#inputNum").val();
  //alert(num);
  $.post(
    "isPrime.php",
    {
      n:num
    },
  	function(data,status){
    $("#isPrime").html(data);
  });
}

isPrime.php

<?php
// get the parameter q from URL
$n=$_REQUEST["n"]; 

if(ctype_digit($n))
{
    if($n>999999999)
    {
        echo "Sorry, for demo purpose, I can only prime test a number less or equal to 999999999";
    }
    else
    {
        $n=intval($n);
        $result=is_prime($n);
        echo $result;
    }
}
else
{
	echo "Please enter a positive integer.";
}

//return 1 if it is a prime
//return a divisor if it is not a prime
function is_prime($n) {

	if($n==1)
		return "$n is not a prime number by definition!";
		
	if($n==2 || $n==3)
		return "$n is a prime number.";
		
	$max_divisor=sqrt(abs($n));
    for($i=2; $i<=$max_divisor; $i++)
    {
    	if($n%$i==0)
    		return "$n is not a prime number because it is divisible by $i.";
    }

    return "$n is a prime number.";
}

demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search