Search code examples
javascriptjqueryajaxhttpduplication

Is it possible to use conditions within an AJAX call to avoid duplicate code?


For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:

var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
        if(URL.length>=2048) {
            // Use POST method to avoid IE GET character limit
            URL = RESOURCE;
            var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
            var jsonDataToSend = JSON.stringify(dataToSend);
            $.ajax({
                type: "POST",
                data: jsonDataToSend,
                dataType: 'json',
                url: URL,
                async: true,
                error: function() {
                    alert("POST error");
                },
                success: function(data) {
                    alert("POST success");
                }
            });
        }else{
            // Use GET
            $.ajax({
                type: "GET",
                dataType: 'json',
                url: URL,
                async: true,
                error: function() {
                    alert("GET error");
                },
                success: function(data) {
                    alert("GET success");
                }
            });
        }

Is there a way of me avoiding writing out this ajax twice? Something like

if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}

N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.


Solution

  • The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.

    Principle:

     var myAjaxSettings = {
                type: "POST",
                data: jsonDataToSend,
                dataType: 'json',
                url: URL,
                async: true,
                error: function() {
                    alert("POST error");
                },
                success: function(data) {
                    alert("POST success");
                }
            }
    
      if ( <condition a> )
          myAjaxSettings.type = "GET";
    
      if ( <condition b> )
          myAjaxSettings.success = function (data) { ...make something different ... };
    
      $.ajax(myAjaxSettings);