Changing the argument passed to jQuery done () callback after successful AJAX call

Here's the script:

I need to get some JSON data via AJAX from the server (ASP.NET MVC application + ServiceStack service). If the user session expires, and instead of returning JSON, I get redirected to the login page, which is automatically launched by jQuery, so the result of the AJAX call ends up being a raw HTML login form. I need to handle these two cases differently:

  • if the result is JSON, then use it to update the user interface with .done()prom
  • if the result is HTML, then the login dialog will appear.

So I need to change the argument passed to the callback done(). Here is what I have tried so far:

function getSomeData() 
{
    return $.ajax(
    {
        /* 
            ...set my AJAX config options... 
        */,
        error: function(xhr, status, errorText)
        {
            // handle the error
        },
        success: function(data) 
        {
            // if the AJAX call returned a login form instead of expected JSON 
            // result (because the user session has expired) then show a 
            // login dialog and resolve the jQuery promise with 'null' instead 
            // of original 'data'

            if (isLoginFormHTML(data)) 
            {
                showModalLoginDialog(data);
                data = null;    // neither this...
                return null;    // ... nor this seem to work!
            }
        }
    });
}

function updateUI()
{
    getSomeData().done(function(jsonData)
    {
        if (jsonData)
        {
            // do something 
        }
    });
}

Unfortunately, regardless of whether I execute data = nulleither return nullin my function success, the argument passed to the return message done()contains the original datareturned from the server, which may be the HTML code for the login form if the session has expired.

So the question is, how do you tell jQuery to pass something else in done()?

PS Of course, I could do a check isLoginFormHTML()inside the method updateUI, but I'm trying to avoid this in order to separate the data search logic and the UI update logic.

+4
source share
1

.then, promises , .

function getSomeData() 
{
    return $.ajax({
        /* 
            ...set my AJAX config options... 
        */,
        error: function(xhr, status, errorText)
        {
            // handle the error
        }).then(function(data){

            if (isLoginFormHTML(data)) {
                showModalLoginDialog(data);
                throw new Error("Unauthorized");..
            }
            return data;
        }
    });
}

:

    getSomeData().done(function(jsonData){
        //yay data   
    }).fail(function(){
       //no data
    });
+1

Source: https://habr.com/ru/post/1537532/


All Articles