tags:

views:

121

answers:

1

For example I have general code for catching json, that says - "its error request". This code is in ajaxComplete, how can I stop executing specific code from ajaxComplete point?

$.post('url', params, 
    function(json){
        if (json.success == false){
             alert('error')
        }
        if (json.success == true){
             alert('success')
        }
    }, 'json'
);

Instead of this code in each ajax request, I want to use something like:

$().ajaxComplete(function(e, xhr){
        if (json.success == false){
             stop_execution_of_post()
        }
        if (json.success == true){
             proceed_execution_of_post();
        }
}

Than in post, you would only to write this:

$.post('url', params, 
    function(json){
        alert('success')
    }, 'json'
);

Is that possible to STOP from execution SPECIFIC ajax function?

A: 

Instead of using ajaxComplete you can override an internal method of jQuery. Obviously you need to be careful because the internal method may change. This is written against jQuery 1.4.

The method is jQuery's httpSuccess(xhr). This takes an XMLHTTPRequest object. When it returns false jQuery's AJAX error handler is called (handleError). Most notably the success handler is not called. Note that the complete handler is always called.

An example:

// Remember the old function
var oldhttpSuccess = jQuery.httpSuccess

// Create the override
jQuery.httpSuccess = function (xhr) {
    // Record the result from the old function
    var success = oldhttpSuccess(xhr)
    // If that's bad return 
    if (!success) {
        return success
    }

    // Do our custom test
    if (weNeedToStop) {
       return false
    }

    // Return the "inherited" success value
    return success
}

So whenever our weNeedToStop test is true, for any ajax response, the success handler is not called.

awatts