0

I'm trying to find a good way to achieve this. If you have any other better suggestions, I'm all ears.

Basically, my site has a bunch of ajax calls. However, I feel like these should be called in a such a way so I don't have to repeat code. Especially the beforeSend method. I don't want to have to type the check methods below everytime. How do I approach this so I dont have to type the check methods everytime? They can have different methods added on to the ones mentioned below, but the 2 below will ALWAYS have to be called. I'm even okay instantiating the ajax call in a different way.

Currently, I have this all over the place in different flavors:

var Params = {};
    Params.type = "POST";
    Params.url = '/this/is/my/url';
    Params.cache = false;
    Params.timeout = 180000;
    Params.processData = true;
    Params.data = {
        action: "ajax",
        method: "coolMethod",
    };

    Params.dataType = "json";
    Params.beforeSend = function () {
         checkIfUserHasLoggedOut();
         checkSomeOtherThings();
    };
    Params.error = function (xhr, status, error) {

    };
    Params.success = function (data) {

    };

1 Answer 1

2

You can use $.ajaxSetup() to setup the default parameters for the ajax request

jQuery.ajaxSetup({
    cache: false,
    timeout: 180000,
    processData: true,
    dataType: 'json',
    beforeSend: function () {
         checkIfUserHasLoggedOut();
         checkSomeOtherThings();
    }
})

then use $.ajax() with the specific parameters, which will change in all calls anyway

$.ajax({
    type: 'POST',
    url: '',
    data: {...},
    success: ....,
    failure: ....
})
Sign up to request clarification or add additional context in comments.

2 Comments

What if i want to add onto beforeSend but not overwrite it?
Well how do I add on to it? suppose i want to run console.log within the particular ajax call. how do i achieve this?

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.