4

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.

2
  • I had an answer for ya until you said "without" duplicating the entire function. That was gonna be my solution, however I agree it would be cleaner to conditionally add the option. I do apologize that that's the only way that I personally would know how to do it. Commented Sep 2, 2011 at 18:53
  • However... for your example, if you want to optionally send a parameter, how about you always send the parameter but set the value to "" with the condition before making your request. Commented Sep 2, 2011 at 18:56

1 Answer 1

13

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