Getting data from server via jquery.ajax very slow

Hi,I have a form with 10 selectbox, I populated the data via jquery.ajax. but it is very slow in requesting to the server.

this is how I do it.

example I am editing the record of a customer

first selectbox (color)
first I will make request to server via jquery.ajax to get the id of the color selected by the customer during on his registration.

$.ajax({
  type:'post',
  url:'getcustomercolorid.php',
  success:function(data){
        var colorid = data.id;
       //send another request to server to get all colors to populate in selectbox.
         getAllcolors(selected_id);
      
 }

});



 function getAllcolors(selected_id){
      $.ajax({
      type:'post',
      url:'getAllcolors.php',
      success:function(data){
            $.each(data,function(key,val){
                if (key == selected_id) { // select the option
                  $('select#colors').append($('<option selected></option>').val(key).text(val));
                } else {
                 $('select#colors').append($('<option></option>').val(key).text(val));
                }
            });
            //calling another function here to load selectbox
           //same procedure above.
          //second selectbox(food)
     }


});

}

Is this the way to populate selectbox with selected value ? but it is very slow…is there other way to do this ?

Thank you in advance.

You don’t need to check if option is selected in the loop.
Instead, just build a list (without anything selected at all) and then say:

$('select#colors').val(selected_id);

This will select corresponding option automatically

Another hint - you can create tags using short format:

$('<option/>')

This is how I’d rewrite .each block:

$.each(data,function(key,val){
    $('<option/>').val(key).text(val).appendTo('select#colors');
});
$('select#colors').val(selected_id);

Thanks for that short format, I just want to ask so there is still two ajax request one for getting the value selected_id and the second for all list ?

It depends on how you store your data at backend.
Of course it would be better to retrieve both selected_id and list with single request, if it’s possible with your architecture

Ok thank you, but does too many request will have performance issue ?

Yes, good practice is to use minimum possible number of requests.
And it’s actual not only for Ajax requests but any other too (like images, stylesheets etc).
Maybe this is not so important while there is only one visitor on the site (you).
But when their number increases you’ll see a difference.

Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.