1

I have ShowExpired() and SessionDestroy() functions running the same jquery. Only difference: I have if statement in ShowExpired().

How can we shrink it?

function ShowExpired() {
    if (isextend == false) {
        $.ajax({
            type: "POST",
            cache: false,
            url: "../../html/frmLogout.aspx/Sessionlogout",
            data: "{userid:" + userid + "}",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            async: false,
            success: function (data, e, jqxhr) {
                if (data.d.result) {
                    window.location.href = '../HTML/frmLogin.aspx';
                }
            },
            error: function (data, e, jqxhr) { alert("logout ERROR=" + data.responseText); }
        });
    }

}


function SessionDestroy() {

        $.ajax({
            type: "POST",
            cache: false,
            url: "../../html/frmLogout.aspx/Sessionlogout",
            data: "{userid:" + userid + "}",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            async: false,
            success: function (data, e, jqxhr) {
                if (data.d.result) {
                    window.location.href = '../HTML/frmLogin.aspx';
                }
            },
            error: function (data, e, jqxhr) { alert("logout ERROR=" + data.responseText); }
        });

}
1
  • If both the functions does the same thing then why do you need to check with if? because none of the ajax part changes like url,data etc.. Then why you need if statement here? Commented Aug 7, 2015 at 3:50

1 Answer 1

0

I had to run it in diffchecker just to make sure. :D https://www.diffchecker.com/jcknyfg4

In this case your first function could shrinked to:

function ShowExpired() {
    if (isextend == false) {
        SessionDestroy();
    }
}

In your example case this is easy. In general case, there are plenty of options to make an ajax call more readable and occupy less space in your code. Google it!

Some pointers:

https://github.com/yaymukund/jquery-ajax-wrap

https://lostechies.com/derickbailey/2012/05/04/wrapping-ajax-in-a-thin-command-framework-for-backbone-apps/

Wrap jQuery's $.ajax() method to define global error handling

Of course writing your own wrapper is also an option. The complexity of it is not high.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.