Reuse AJAX calls with jQuery

Asked

Viewed 144 times

1

Hello

It is very common to see on the internet calls ajax blocks that always repeat exhaustively the same structure, I would like to improve my calls using parameterization patterns and save code of my processes.

Current pattern:

$.ajax({
        type: "GET",
        url: url,
        dataType: "html",
        timeout: 30000,
        data: 
        {
            //parametros
        },
        success: function(data)
        {
            //caso sucesso...
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            //caso erro
        },
    });     

I would like to propose a role that is centralizing, something like chamarAjax("POST", url, array(parameters))

But that is where the doubts arise: 1) Whereas parameters can be an array (key/value) how to pass them considering they can be 'n' ?

2) How to work with the return of the executed function (Success, error, complete) in the process/script that called the function ?

I looked for examples of this paradigm but found nothing, I appreciate any indication

  • You can instead use ajax to use AXIOS. It reduces the code that is used a bit. https://github.com/axios/axios

  • 1

    Thanks @Lucasbrogni for the nomination, I will evaluate

  • 1

    pq not using $.post and $.get?

  • @Tobiasmesquita nothing against, the point is not themselves, but to concentrate calls. For example instead of having a $.get('user/blablabla') and all its configuration (with timeout for example) I wanted to have something simpler in hand

  • You cannot put in a Function with all the parameters?

  • @Ricardopunctual yes, that’s the idea ! But when I talk about parameters like date (or an array) and at the same time, like Interceptor Success/error/, Voce happens to have some example ?

  • @DVD thanks for sharing, I will evaluate !

  • 1

    was going to post something similar to @dvd posted, but his example is very good, taking advantage of the done to call the function and returning date, very good

  • @dvd was perfect what you sent, gave to explore well and generate for my pattern smoothly. Thanks again !

  • Good... I will post as an answer because it gave me work rs..

Show 5 more comments

2 answers

2


Young man, the call of $.ajax returns a Promise (most likely not native, but jQuery’s). That way, you can call a function that returns this Promise, allowing parameters, such as function $.ajax already does, but leaving predefined parameters. Thus, you can combine the call from $.ajax and $.extend to increase the power of reuse.

I’ll give you an example of how to upload files with jQuery. I usually use the presets within a function, but not leaving the code plastered:

function ajaxUpload(options)
{

    options = $.extend({}, {
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
    }, options);


    return $.ajax(options);
}

That way, the call could be made that way:

ajaxUpload({
    url: '/upload/imagem',
    data: data,
}).success(function () {
    console.log('upload da imagem concluído')
})


ajaxUpload({
    url: '/upload/texto',
    data: data,
    success: function () {
       console.log('upload do texto concluído')
    }
})

Note that I make two calls, reusing the same "settings" of Ajax. Important to note that in the second call I use the success as part of options, showing that it is possible to have high usability both in the return and by the parameter.

Observing: Depending on your use, you don’t even need to create a function, since jQuery has several methods to facilitate Ajax requests, as you already have predefined request options.

For example:

  • $.post - Define a request using the POST method
  • $.get - Defines a GET request
  • $.getJSON - Defines a request that returns JSON already "parsed".

Exemplifying the use of $.post:

  $.post('/url', {id: 1}, function (response) {
        console.log(response);
  })
  • thanks for the answer and for the knowledge, really got much more 'elegant' this way. If it’s not too much to ask, you could help with this topic : https://answall.com/questions/314278/chamar-m%C3%A9todo-ajax-sincrono-sem-asyncfalse

0

Hi @Mcunha98,

You can create a structure with PHP/Jquery. Where the ajax will be as a centralized file, and every time you run a command, define that file by sending values to it, receiving via GET/POST and assigning the variables via js.

for example:

  • menu and products menu.
  • Click on menu clients>new registration
  • when clicking on new registration, make a . load() of the form, where in this form will be the ajax. This form will be called by all resources(customers/products, etc...)
  • the form will receive a parameter, defining from which screen and other items defined as convention of its structure.
  • this I have done, the question is precisely that as the thing grows it starts to have several times the same 'block' at different moments of the code and this is what I want to simplify with a function that already does the direct interface with ajax

  • Try creating a Function nameFunc(){ by placing ajax here and other variables in Success and before }. Then this file would be referenced via src script or inlcude, calling it with its parameters

Browser other questions tagged

You are not signed in. Login or sign up in order to post.