Reusing AJAX calls with jQuery

1

Hello

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

Current status:

$.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 function that is centralizing, something like callAjax ("POST", url, array)

But that's where the doubts come: 1) Considering that parameters can be an array (key / value) how to pass them whereas they can be 'n'?

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

I searched for examples of this paradigm but found nothing, thank you for any indication

    
asked by anonymous 13.07.2018 / 19:59

2 answers

2

Young, the call of $.ajax returns a Promise (most likely not the native, but jQuery). This way, you can call a function that returns this Promise , allowing parameters, as the $.ajax function already does, but leaving pre-defined parameters. So you can combine the $.ajax and $.extend call to increase reuse power.

I'll give you an example of how I do when I need to upload files with jQuery. I usually use the pre-settings inside a function, but not leaving the code embedded:

function ajaxUpload(options)
{

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


    return $.ajax(options);
}

In this way, the call could be made this 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')
    }
})

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

Note : Depending on your usage, you do not even need to create a function, since jQuery has several methods to facilitate Ajax request, since they already have the pre-defined request options. p>

For example:

  • $.post - Defines a request with the POST method
  • $.get - Defines a GET request
  • $.getJSON - Defines a request that returns JSON already "parseado".

Exemplifying the use of $.post :

  $.post('/url', {id: 1}, function (response) {
        console.log(response);
  })
    
14.07.2018 / 21:27
0

Hello @ MCunha98,

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

For example:

  • Customers menu and Product menu.
  • Click on the Customers menu> New Registration
  • When you click on new register, it makes a .load () of the form, where in this form will be ajax. This form will be called by all the resources (clients / products, etc ...)
  • the form will receive a parameter, defining which screen and other items are defined as the convention of its structure.
13.07.2018 / 20:32