Thursday 24 March 2016

How to Stop ajax requests in jQuery?

How to Stop ajax requests in jQuery

HTML Code



<!--- HTML Part --->
<form id="formId" method="POST" onsubmit="return saveData()">
<input name="formsubmit" type="hidden" value="1" />
    First Name:  <input name="first_name" type="text" />
    <br />
Last Name:  <input name="last_name" type="text" />
    <br />
Email: &nbsp;   &nbsp;  &nbsp;   &nbsp;<input name="email" type="text" /><br />
<input type="submit" value="Click to Submit" />
</form>
<!--- HTML Part --->



jQuery/JavaScript Code



<!--- Javascript Part --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
var request=0;
    function saveData() {
        if(request!=0){
   request.abort();
  }
         request=$.ajax({
            url: "ajax.php",
            method:"post",
            data: $('form#formId').serialize()+'&phone=789797522&city_id=1',
            cache: false,
            success: function(msg) {
                console.log(msg);
    request =0;
            }
        });
  
        return false;
    }

</script>
<!--- Javascript Part --->



PHP Code



if(!empty($_POST)){
    echo "<pre>";
    print_r($_POST);
 echo "</pre>
";
    /** You can write your code here **/    
    

/** You can write your code here **/        
    die;
}



PHP Output Code



Array
(
    [formsubmit] => 1
    [first_name] => Raj
    [last_name] => sinha
    [email] => raj@no-spam.ws
    [phone] => 789797522
    [city_id] => 1
)