views:

398

answers:

2

Hi, what im wanting to achieve is if a error appears ( one which I have come up with ) and contains the word 'error' then the function stops in its tracks. What the function basically consists of is 5 ajax requests, when one is successful the other kicks in.. like so..

function thing() {
    $.ajax({
        ...
        ...  
        success: 
        function(html){
            errorGet(html);   
            $.ajax({
            ...
            ...  
            success: 
            function(html){
                errorGet(html);
                    ...
                ... 

I have a function in place 'errorGet()' to try and stop the function;

function errorGet(data){
    var re = /error/mgi;
    if( data.search( re ) == 0 ){
        thing.stop;
    }
}

but i know thing.stop doen't work but does anyone know how to stop the process?

+1  A: 

Have you tried throwing an exception?

throw "there was an error so I am going to stop";
Pointy
`function errorGet(data){`` if( data.search( /error/ ) != "-1" ){`` throw "";`` }``}`worked fine.
Phil Jackson
+3  A: 

You could have a function that calls your AJAX requests without being asynchonous. That way that don't have to be netsed, and you can just return to exit the function.

function thing() {
    var stop = false;

    $.ajax({
        async: false,
        ...  
        success: 
        function(html){
            stop = errorGet(html);
        }
    }

    if(stop) {
        return false;
    }

    $.ajax({
        async: false,
        ...  
        success: 
        function(html){
            stop = errorGet(html);
        }
    }
}

function errorGet(data){
    var re = /error/mgi;
    if( data.search( re ) == 0 ){
        return false; //no error
    }
    return true;
}
mr.moses
This won't work because the ajax mechanism will return before the HTTP request completes, and thus before the error check is made in the "success" callbacks. In other words, the code will get to the "if (stop)" point quite some time before the errorGet function is ever called.
Pointy
Pointy, it will wait for $.ajax() to complete, because it's synchronous (async: false). sounds like a way to go.
parserr
Oh durrr. Sorry!
Pointy