How to group rules in jquery

Hi, I have a simple question. I have this code below, I use ajax three times in very similar ways, only the variables are the data transferred and the target identifier. Is there a way to group these instructions into a simple one? Thanks D.

$('#fld_email').focusout(function() {
                    var request_email = $(this).val();              
                    $.ajax({type:"GET",
                            url: "autocomplete.asp",
                            data: "fld=firstname&email="+request_email,
                            beforeSend: function(){$('#fld_firstname').addClass('ac_loading');},
                            success: function(msg){$('#fld_firstname').val(msg);$('#fld_firstname').removeClass('ac_loading'); }
                          });   
                    $.ajax({type:"GET",
                            url: "autocomplete.asp",
                            data: "fld=lastname&email="+request_email,
                            beforeSend: function(){$('#fld_lastname').addClass('ac_loading');},
                            success: function(msg){$('#fld_lastname').val(msg);$('#fld_lastname').removeClass('ac_loading');}
                          });   
                    $.ajax({type:"GET",
                           url: "autocomplete.asp",
                           data: "fld=phone&email="+request_email,
                           beforeSend: function(){$('#fld_phone').addClass('ac_loading');},
                           success: function(msg){$('#fld_phone').val(msg);$('#fld_phone').removeClass('ac_loading');}
                          });   
                    }
                    );
+5
source share
2 answers

to try:

$('#fld_email').focusout(function() {
    var request_email = $(this).val();
    processAjax("fld=firstname&email="+request_email, '#fld_firstname');
    processAjax("fld=lastname&email="+request_email, '#fld_lastname');
    processAjax("fld=phone&email="+request_email, '#fld_phone');
});

function processAjax(data, id){
    $.ajax({type:"GET",
           url: "autocomplete.asp",
           data: data,
           beforeSend: function(){$(id).addClass('ac_loading');},
           success: function(msg){$(id).val(msg).removeClass('ac_loading');}
    });   
}
+4
source

Use the object and control structure:

var fields = {firstname:1, lastname:1, phone:1};
for (field in fields) {
  $.ajax({
    type:"GET",
    url: "autocomplete.asp",
    data: "fld=" + field + "&email=" + request_email,
    beforeSend: function() {
      $('#fld_'+field).addClass('ac_loading');
    },
    success: function(msg) {
      $('#fld'+field).val(msg);
      $('#fld'+field).removeClass('ac_loading');
    }
  });
}
+1
source

All Articles