Home > Software design >  JQuery Ajax not replacing div element with text file
JQuery Ajax not replacing div element with text file

Time:01-14

So, I'm quite new to JQuery, and AJAX in general. I've made an app to retrieve data from Spotify's API, which writes to song.txt (This part works just fine. It updates every second, as it should.) and the HTML file will pull the contents of song.txt and change the div with id of 'track'

 <!DOCTYPE html>
<html>
    <head>
        <title>Camashima's Site</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
        <script type="text/javascript">
            setInterval(function () {
                $(document).ready(function () {
                    $('#track').load('../output/song.txt');
                });
            });
        </script>
    </head>
    <body>
        Currently Playing:
        <div id="track">
            .
        </div>
    </body>
</html>

The JS code posts the html file to the server just fine, and I see Currently playing: but nothing else. So that tells me it's not the issue. So, what am I doing wrong here? It should be loading song.txt into the "track" div, right?

Also, I'm using Goorm-ide to host my container, and the console isn't as in-depth as chrome's dev tools. Expected: "track" div to be replaced with song.txt contents

Result: Nothing happens.

CodePudding user response:

Whether or not the AJAX part works, the main problem here is that you're (1) adding tons of document.ready events and (2) doing so indefinitely in very rapid succession.

You can correct this by (1) using one document.ready event and setting your interval within that and (2) providing a delay to the interval, even if it's just one second. For example:

$(document).ready(function () {
  // execute this code once, and only once, when the document is ready
  setInterval(function () {
    $('#track').load('../output/song.txt');
  }, 1000);  // perform this interval operation every 1000 ms
});

From there, you can then begin to reasonably debug the AJAX issue (if there even is one). I realize in a comment on the question you indicated that Chrome developer tools are disabled. So you'll either need to correct that or find another tool to use to debug it. But you're essentially going to want to observe the AJAX requests and responses. Confirm that the address being requested is what you expect it to be, and observe the response from the server. The client-side code here is extremely simple and "works" just fine, but if the overall result isn't what's expected then your only recourse is to debug those interactions with the server.

  •  Tags:  
  • Related