Asked 2 years ago
24 Jun 2021
Views 401
Myrtie

Myrtie posted

How do I execute a javascript after Ajax load?

How do I execute a javascript after Ajax load?
sarah

sarah
answered Apr 28 '23 00:00

To execute JavaScript code after an AJAX load using jQuery, you can use the . load () method with a callback function.

Here's an example:



<div id="myDiv">
  <!-- Content will be loaded here via AJAX -->
</div>

<button id="loadButton">Load Content</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    $("#loadButton").click(function() {
      $("#myDiv").load("ajax_content.html", function() {
        // This function is called after the content is loaded via AJAX
        myFunction();
      });
    });
  });

  function myFunction() {
    // Your code here
    console.log("Content loaded via AJAX.");
  }
</script>

In this example, the .load() method is used to load the content from the ajax_content .html file into the #myDiv element when the user clicks on the #loadButton button. The second argument to the .load() method is a callback function that is called after the content is loaded via AJAX. In this case, the myFunction() function is called, which logs a message to the console.

You can replace the myFunction() function with your own JavaScript code to execute after the AJAX load.






Post Answer