How to run a first instance of ajax jquery when page loads

68 Views Asked by At

I have a jquery and ajax that performs a query and shows a table when a button is clicked. The problem is that when the page loads for first time, the query not run and do not shows anything, so the button has to be clicked to start showing the query result. Is there a way that the query runs when page loads? and then just use the button. My code is:

$(document).ready(function() {
  $("#display").click(function() {
    $.ajax({ //create an ajax request to display.php
      type: "GET",
      url: "genquery.php",
      dataType: "html", //expect html to be returned                
      success: function(response) {
        $("#responsecontainer").html(response);
        //alert(response);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
  <tr>
    <td> <input type="button" id="display" value="Buscar" /> </td>
  </tr>
</table>
<div id="responsecontainer" align="center">

</div>

Thanks in advance!

2

There are 2 best solutions below

0
Barmar On BEST ANSWER

Just call click() on the element to simulate a click.

$(document).ready(function() {
  $("#display").click(function() {
    $.ajax({ //create an ajax request to display.php
      type: "GET",
      url: "genquery.php",
      dataType: "html", //expect html to be returned                
      success: function(response) {
        $("#responsecontainer").html(response);
        //alert(response);
      }
    });
  }).click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" align="center">
  <tr>
    <td> <input type="button" id="display" value="Buscar" /> </td>
  </tr>
</table>
<div id="responsecontainer" align="center">

</div>

0
El_Vanja On

You could extract the function you're calling in the click handler and call it within ready.

$(document).ready(function() {
  const displayContent = () => {
    $.ajax({ //create an ajax request to display.php
      type: "GET",
      url: "genquery.php",
      dataType: "html", //expect html to be returned                
      success: function(response) {
        $("#responsecontainer").html(response);
        //alert(response);
      }
    });
  }
  displayContent();
  $("#display").click(displayContent());
});