Skip to content
Advertisement

How to stop jQuery .ajax() execution when success is false?

I have this code which works.

$.ajax({
     type: "GET",
     url: "includes/process.php",
     data: "captcha=" + captcha,
     success: function(data) {
         if(data == 'true')
             alert("OK");
         else
             alert("not ok");
     }
});

However I have some more code after that like:

var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;

$.ajax({
    type: "POST",
    url: "bin/process.php",
    data: dataString,
    ...
    ...
    ...etc

However, I need to stop the script when success:function(data) is false.

So, I thought that return false; should stop the execution

    success: function(data) {
        if(data == 'true') {
            alert("OK");
        } else { 
            alert("not ok"); 
            return false; 
        }
    }

, however it is not working and the code after $.ajax is executed anyway.

How to stop the script when the success is false?

Any advice? Thanks in advance.

ADDITIONAL INFO: I have another ajax call which I want to execute when success is true:

var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
$.ajax({
    type: "POST",
    url: "bin/process.php",
    data: dataString,
    success: function() {
       alert ('mail was sent OK');                                 
    }
});

How to execute this code only after success of the first ajax call?

Advertisement

Answer

Your extra code should be in the callback itself.

$.ajax({
    type: "GET",
    url: "includes/process.php",
    data: "captcha=" + captcha,
    success: function(data) {
        if (data == 'true') {
            alert("OK");
            // more code
            var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
            // ... second ajax call
        } else {
            alert("not ok");
        }

    }
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement