Multiple ajax requests using jquery

Asked

Viewed 440 times

0

I have this code over and over and I wanted to simplify it into a kind of plugin or function. Information I usually use, Type => 'get' or 'post' and the url, and the return I deal with in sequence with jquery.

$.ajax({
    type: '',
    url: '' ,
    dataType : 'json',
    //data: jsonString,
    beforeSend: function () {
        //SPINNER
    },
    success: function (data, textStatus, jqXHR) {

    },
    complete: function () {

    },
    error: function (jqXHR, textStatus, errorThrown) {

    }
});

4 answers

1

In my ajax requests I usually create a class js and there are generic methods, but by semantics I end up separating gets, posts.. Below is an example I use for Post

function BaseEnviaPost(url, objeto, onSuccess, onError) {
    $.ajax({
        url: url,
        type: "POST",
        data: objeto,
        datatype: "json",
        success: function (data) {
            onSuccess();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            onError(jqXHR, textStatus, errorThrown);
        }
    });
}

When I need to use, the call is simplified like this:

var success = function (data) {
   //ação
}

var error = function (jqXHR, textStatus, errorThrown) {
    //ação
}

function BaseEnviaPost() {
    var url = "";
    var data = {};
    BaseEnviaCreate(url, data, success, error)
}

0

Dude, I think the more game explore a newer technologies than Dao a greater flexibility with Ajax calls. For example... Angularjs, makes it much easier. Oce would create a service and in that service would use $http.get(<url>) and that’s it. Anyway. It’s a hint but it doesn’t answer the question.

now, I would rather write a little function but or so to solve your problem:

function (url, type, successFn, errorFn = undefined){
   // escreve os códigos aqui...
}

Actually, it doesn’t help to do that, it’s swap 6 by half a dozen. Give a look at the Angularjs, super easy!

https://www.w3schools.com/angular/angular_services.asp

  • Because then , I’m thinking about Angularjs for the practicality of some things, the separation of layers is very well organized but I lack time to learn Angularjs and make a system with logins and control of access levels at the moment. But Thanks!

  • It’s Carlos, but you’ll see that the organization and practicality of Angular will save you a lot of time up front. Using auth0 libs also helps a lot! but anyway... good luck!

0

Function:

function funcaoAjax(type, url, dateType, beforesend, success, complete, error){
  $.ajax({
      type: type,
      url: url,
      dataType: dateType,
      beforeSend: beforesend,
      success: success,
      complete: complete,
      error: error
  });

}

To call:

funcaoAjax("POST", "minnhaurl", "POST", function(){
  // código do beforesend
}, 
function(data, textStatus, jqXHR){
  // código do success
},
function(){
  // código do complete
},
function(jqXHR, textStatus, errorThrown){
  // código do error
});

0

Creates a function around this ajax with some assumptions that can be changed, and uses the fact that ajax returns a Promise-like object. Then you’ll repeat a lot less code.

function ajax(options) {
  return $.ajax({
    method: options.method || 'GET',
    url: options.url || './meu/endpoint/favorito,
    dataType: 'json',
    data: options.data || {},
    beforeSend: function() {
      //SPINNER
    },
  }).fail(function() {
    // aqui tratas dos erros que possam haver
    console.log('Erro...');
  });
}

And then to use:

ajax({url: './endpoint1').then(function(resposta){
    console.log(resposta);
});

Browser other questions tagged

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