How to get external file data in div using ajax?

To get the data from another file, Ajax is the best choice. As we know that AJAX work without reloading the page, This feature make AJAX more powerful and usable. So to do this let’s see an example. In this example, we will get data from another file. How to get external file data in div using ajax?

Step 1 Here we create a text file named sample.txt and add some text in it. Later we will get its content in div.

Step 2 Now create a simple HTML file like below.


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".btn").click(function()
  {
    $.ajax({
    url: "sample.txt", 
    success: function(data)
    {
      $("#mydiv").html(data);
    }
    });
  });
});
</script>
</head>
<body>

<div id="mydiv"><h2>This text will be change after click the below button</h2></div>

<button class = "btn">Click to get data</button>

</body>
</html>
Now when we click on button, the content of div will be replaced with the text which we had written in sample.txt file.

How to get external file data in div using ajax?expoundsofttechsolution