Recursive Ajax Call

index.html

<!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script type="text/javascript" src="recursiveAjax.js"></script>
</head>
  <body>
    <label>Enter a positive number: </label>
    <input id="aNum" type="number" min="1" max="1000"/>
    <button id="myBtn" type="submit" value='submit'>Submit</button>
    <div id="counter"></div>
  </body>
</html>

recursiveAjax.js

$(document).ready(function(){
  $("#myBtn").click(function(){
    var aNum=$('#aNum').val();
    var posIntReg=new RegExp(/^[0-9]+$/); //regex pattern for positive integer

    if(posIntReg.test(aNum) && aNum>0 && aNum<=1000)
    {
      //disable the submit button
      $(this).attr('disabled','true');$(this).css('cursor','progress');$(this).html('counting');
    	
      //Initiate the recursive ajax call
      recursiveAjaxCall(parseInt(aNum),0);
    }
    else
    {
      alert("Enter a number greater than 0 and less or equal to 1000!");
    }
  });
});

function recursiveAjaxCall(aNum,currentNum)
{
  $.ajax({
    url: 'incrementer.php',
    data: {num: currentNum},
    success: function(data,status)
    {
      $("#counter").html('counter: '+data);
      if(data<aNum)
      {
        //recursively call this function if the data recieved from backend is less than the input number
        recursiveAjaxCall(aNum,data);
      }
      else
      {
        //enable the submit button
        $('#myBtn').css('cursor','pointer');$('#myBtn').html('Submit');$('#myBtn').removeAttr('disabled');
      }
    },
    async:   true
  });
}

incrementer.php

<?php
	//get the number
    $num=$_REQUEST['num'];

    ///////////////////////
    //Do some fancy work...
    ///////////////////////
    
    //Increment by 1
    echo $num+1;
?>

demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search