Jinbom Heo
Jinbom Heo

Reputation: 7400

jquery exit function in ajax call

Is there a way to exit a function, depending on the result of an GET request.

For example, in the below function, hi, if the GET results in data, where data === '1', I want to exit the function.

function hi () {
    $.ajax({
        url: "/shop/haveItem",
        type: "GET",
        success: function (data) {
            if (data == '1') {
                // exit hi() function
            }
        }
    });
    // some executable code when data is not '1'
}

How can I go about accomplishing this?

Upvotes: 6

Views: 19582

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388336

I think the solution can be something like this

function hi () {
    $.ajax({
        url: "/shop/haveItem",
        type: "GET",
        success: function (data) {
            if (data == '1') {
                ifData1();
            } else {
                ifDataNot1()
            }
        }
    });
}
function ifData1 () { /* etc */ }
function ifDataNot1 () { /* etc */ }

If you have an ajax function, you should always work with callback functions. If you make an ajax function synchronous, then the browser will be blocked for the duration of ajax call. Which means that the application will remain non-responsive during the duration of the call.

Upvotes: 9

TimNguyenBSM
TimNguyenBSM

Reputation: 827

You should be able to return false to simulate "exit".

function hi()
{
    $.ajax({
            url: "/shop/haveItem",
            type: "GET",
            async:false,
            success: function(data){
                if(data == '1')
                    return false
            }
        });

    //some executable code when data is not '1'
    ...
}

Upvotes: 2

KraigBalla
KraigBalla

Reputation: 363

Creating a global flag variable I think would work the best. Tested and working!!

window.flag = [];

function hi()
{
    $.ajax({
        url: "/shop/haveItem",
        type: "GET",
        async:false,
        success: function(data){
            if(data == '1')
                flag = true;
        }
    });

    if (flag) {
        return false; 
    }


//some executable code when data is not '1'
...
}

Upvotes: 0

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22104

One thing you can do is have a flag variable. Assign it to true or false, depending on if you want to exit or not.

function hi()
{
var flag=false;    
$.ajax({
            url: "/shop/haveItem",
            type: "GET",
            async:false,
            success: function(data){
                if(data == '1')
                    flag=true;
            }
        });
if ( flag ) return;
    //some executable code when data is not '1'
    ...
}

Upvotes: 0

Related Questions