Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine two Ajax requests that runs on two separate events

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading