skip to Main Content

Whenever clicking the button, target file has fetched i.e. “demo.txt” (checked in network) but file content is not displaying, what’s wrong?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#button").click(function(){

        $.ajax({url: "http://localhost/suman_php/JQ_AJAX/demo.txt", 
            type:"GET",
            success: function(data,status){
                alert(status);
                $("#div1").html(data);
    }});
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button id="button">Click to get Content</button>

</body>
</html>

3

Answers


  1. Chosen as BEST ANSWER
        $(document).ready(function(){
    
      $("button").click(function(){
      $.get("http://localhost/suman_php/JQ_AJAX/demo.txt", function(data, status){
        alert(status);
        $("#show").html(data);
      });
    
    });
    
    });
    

    What should be modified in this code to view the file content?


  2. a) I suggest you to use “method” instead of “type”

    b) define an “error” function, as defined here: https://api.jquery.com/jquery.ajax/ that may give you some info why the request failed.

    Login or Signup to reply.
  3. I think you are trying to display text file content in your Div while clicking the button.
    You don’t need GET method unless you are trying to get specific data from link to use it somewhere else in the backend such as using it in PHP.
    Try this:

    $.ajax({
                url: "http://localhost/suman_php/JQ_AJAX/demo.txt",
                async: false,   //to wait for text to load
                dataType: "text",  // jQuery will return the text data from the file
                success: function( data, status ) {
                  alert(status);
                  $("#div1").html(data);
                }
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search