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); }
        });

}
Elyor
  • 5,396
  • 8
  • 48
  • 76
  • 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? – Guruprasad J Rao Aug 07 '15 at 03:50

1 Answers1

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.

Community
  • 1
  • 1
DDan
  • 8,068
  • 5
  • 33
  • 52