Home > Software design >  Combine two Ajax requests that runs on two separate events
Combine two Ajax requests that runs on two separate events

Time:08-05

I'm using the following code to send two ajax requests. One is send on page load which loads the default content and the other one is for the buttons so if a user click a certain button content is changed according to that.

I'm wondering if there is a way to simplify the following code. Any input would be much appreciated.

< script >
  $(document).ready(function() {

    $.ajax({
      type: "POST",
      url: "filter.php",
      dataType: "html",
      data: 'default',
      cache: false,
      success: function(html) {
        $("#responsecontainer").html(html);
        alert(response);
      }
    });


  });

$(".myclass").click(function() {

  var value = $(this).attr('value');
  console.log(value);
  $.ajax({
    type: "POST",
    url: "filter.php",
    dataType: "html",
    data: '&type='   value,
    cache: false,
    success: function(response) {
      $("#responsecontainer").html(response);
      alert(response);
    }

  });
}); <
/script>

CodePudding user response:

Consider the following.

$(function() {
  function getContainerData(myData) {
    $.ajax({
      type: "POST",
      url: "filter.php",
      dataType: "html",
      data: myData,
      cache: false,
      success: function(html) {
        $("#responsecontainer").html(html);
        console.log(html);
      }
    });
  }

  getContainerData("default");

  $(".myclass").click(function(event) {
    getContainerData('&type='   $(this).attr("value"));
  });
});

This created a function that allows you to enter specific Data to pass in an AJAX call.

You might consider passing in an Object.

{ type: "default" }

Or

{ type: $(this).attr("value") }

This will be translated by the AJAX to the proper POST values.

  • Related