-1

I am new to the ajax. This is the simple code i am trying to compile. I dont know why it is not able to get the contents of the file.

Here is my code:-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url:"text.txt", success: function(result){
            $("#div1").html(result);
        }}).fail( function() {
                alert('Failed to get the content');
        });

    });
});
</script>
</head>
<body>

<div id="div1"><h2>Ajax</h2></div>

<button>Get Content</button>

</body>
</html>

please someone tell me where i am going wrong.

Thnaks in advance.

UPDATE :- After some trial and error and i got the desired result. I missed out declaration of datatype that is dataType:"text" Now code is working perfectly.

abhillier
  • 214
  • 2
  • 13

3 Answers3

0

Where is your file is located? Make sure you have text.txt file in the same location as your html page.

  • Please do not post comments as answers, Instead ANSWER the question with a valid answer to earn enough rep to comment – mplungjan Feb 05 '16 at 12:51
0

Your code works perfectly if file containing jquery code and text.txt file both are in same folder.

-1

Try error handling like this:

$(document).ready(function() {
  $("button").click(function() {
    $.ajax({
      url: "text.txt",
      success: function(result) {

        $("#div1").html(result);

      },
      error: function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }
    });
  });
});

instead of using fail

Supun Praneeth
  • 3,087
  • 2
  • 30
  • 33