methuselah
methuselah

Reputation: 13206

Dealing with jQuery statement with lots of AJAX calls

What is the best way to deal with an jQuery statement that has many AJAX calls?

The code below seems slightly inefficient.

$("#search_building").on("change blur", function () {
    var building = $("#search_building").val();
    var room = $("#search_room").val();
    var dept = $("#dept").val();
    var dataString = 'room=' + room + '&' + 'building=' + building + '&' + 'dept=' + dept;
    $.ajax({
        type: "POST",
        url: "process_building.php",
        data: dataString,
        cache: false,
        success: function (html) {
            $('#search_room').html(html);
        }
    });
    $.ajax({
        type: "POST",
        url: "process_timetableMon.php",
        data: dataString,
        cache: false,
        success: function (html) {
            $('#grid2_mon').html(html);
        }
    });
    $.ajax({
        type: "POST",
        url: "process_timetableTue.php",
        data: dataString,
        cache: false,
        success: function (html) {
            $('#grid2_tue').html(html);
        }
    });
    $.ajax({
        type: "POST",
        url: "process_timetableWed.php",
        data: dataString,
        cache: false,
        success: function (html) {
            $('#grid2_wed').html(html);
        }
    });
    $.ajax({
        type: "POST",
        url: "process_timetableThu.php",
        data: dataString,
        cache: false,
        success: function (html) {
            $('#grid2_thu').html(html);
        }
    });
    $.ajax({
        type: "POST",
        url: "process_timetableFri.php",
        data: dataString,
        cache: false,
        success: function (html) {
            $('#grid2_fri').html(html);
        }
    });
});

Upvotes: 1

Views: 161

Answers (1)

karancan
karancan

Reputation: 2162

Replace all your AJAX calls with one AJAX call:

$.ajax({
  type: "POST",
  dataType: "json", 
  url: "process_all.php",
  data: dataString,
  cache: false,
  success: function (data) {
     //This is your json data
     //data[n] is just an illustration of how you could use your json that you get back.
     //In reality it depends on how you do your server side processing
     $('#grid2_day1').html(data[0]);
     $('#grid2_day2').html(data[1]);
     $('#grid2_day3').html(data[2]);
     $('#grid2_day4').html(data[3]);
     $('#grid2_day5').html(data[4]);
  }
});

Also note that the URL being called would be one place where you do all your processing or at least trigger whatever processing you need to do.

To get back JSON after processing, call JSON encode the data using PHP json_encode()

Upvotes: 2

Related Questions