Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally adding option to jQuery Ajax call

I have the following working Ajax call -

    $.ajax({
        url: ajaxUrl,
        type: sendHttpVerb,
        dataType: 'json',
        processData: false,
        contentType: 'application/json; charset=utf-8',
        complete: function () {
            setTimeout($.unblockUI, 2000);
        },
        success: function (response, status, xml) {
            clearTimeout(delayLoadingMsg);
            $.unblockUI();
            callbackFunction(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            clearTimeout(delayLoadingMsg);
            $.unblockUI();
            dcfForm.ajaxErrorDisplay(jqXHR, textStatus, errorThrown)
        }
    });

My problem is the I conditionally want to add an option when I invoke the Ajax call. For example, adding data: sendRequest before I issue the Ajax request.

My problem I cannot find an example for the syntax on how to do this without completely duplicating the entire function.

like image 889
photo_tom Avatar asked Dec 16 '22 09:12

photo_tom


1 Answers

what about a ternary operation:

$.ajax({
     data: condition ? sendRequest : undefined,
     ... the rest
});

If that's not your taste, some people seem to forget $.ajax doesn't take a long group of paramters, but an object:

var ajax = {};
ajax.success = function (data) { ... };
ajax.type = 'GET';

if (myCondition) {
    ajax.data = sendRequest;
}

$.ajax(ajax);
like image 147
Joe Avatar answered Dec 21 '22 22:12

Joe