Search code examples
javascriptjqueryajaxjplayer

Jquery AJAX - Update span of text when this button is clicked


I've been trying to figure out how to use ajax in this simple function.

I have a span that displays how many songs a user has in their playlist. It's simply showing how many values exist inside of a localStorage key.

<span id="count-songs-span">
    <script>
        var countSongs = JSON.parse(localStorage.playlist).length;
        document.write(countSongs);
    </script>
</span>

We are using jPlayer and we have a playlist set up. When you remove a song from the playlist (by clicking a remove button), we would like to update the contents of that div, "count-songs-span", with the new count. For now, it only works when we refresh the page, but we'd like it to update using ajax.

We have added a click event for the remove button here:

$('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
    window.setTimeout(updatePlaylist, 500);
});

updatePlaylist() is as follows:

function updatePlaylist(){
      playlist = myPlaylist.playlist;
      storage.set( 'playlist', playlist );
    }

The click event is saving the list to localStorage, and that's fine. But before that, we'd like to update the countSongs variable with ajax.

I have this snippet from another website, and I've tried to adapt it to my site, but I just can't get it to work. It's just not the right code for my site.

$.ajax({
           type : "get",
           dataType : "json",
           url : ajax_object.ajaxurl,
           data : {action: "get_media", id : id},
           success: function(obj) {
              if(obj.length == 1){
                player.add( obj[0], true );
                updatePlaylist();
              }else if(obj.length > 1){
                player.setPlaylist(obj);
                player.play(0);
                updatePlaylist();
              }
           }
        });

Can anyone help me use ajax to update the "count-songs-span"?

Thanks so much if you can help.


UPDATE:

Here is a demo of what is being stored.

The method to store the playlist data:

function updatePlaylist(){
      playlist = myPlaylist.playlist;
      storage.set( 'playlist', playlist );
    }

Anywhere we need to store the playlist information, we call that method - updatePlaylist()

This is an example of what is being stored:

[{"title":"Mauvais Temps","artist":"Right Beat Radio","mp3":"/mp3s/MauvaisTemps.mp3"},{"title":"Line Steppers","artist":"Right Beat Radio","mp3":"/mp3s/LineSteppers.mp3"},{"title":"Try My Best","artist":"Right Beat Radio","mp3":"/mp3s/TryMyBest.mp3"},{"title":"San Ignacio","artist":"Right Beat Radio","mp3":"/mp3s/SanIgnacio.mp3"}]

So when we want to count the number of songs in the playlist, we use this (the localStorage key is called "playlist":

var countSongs = JSON.parse(localStorage.playlist).length;
document.write(countSongs);

UPDATE #2:

Screenshot:

https://rightbeatradio.com/wp-content/uploads/2015/09/Screen-Shot-2015-09-07-at-9.13.34-AM.png

Hopefully this screenshot will help. You can see the playlist there, and above that, you will see the number of songs currently in the list (7 songs).

Beside each song on the list, there's a remove (x) button. This button allows a user to remove a song from the list.

Upon clicking that button, these functions fire:

//Remove Item from Playlist
    $('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
      window.setTimeout(updatePlaylist, 500);
    });

// update playlist
    function updatePlaylist(){
      playlist = myPlaylist.playlist;
      storage.set( 'playlist', playlist );
    }

Somewhere in there, we'd like to also count the number of items in the localStorage, "playlist" key, and update the count by using ajax.

Here's the HTML of the span that counts the number of songs in the playlist:

<span id="count-songs-span">
  <script>
    var countSongs = JSON.parse(localStorage.playlist).length;
    document.write(countSongs);
  </script>
</span>

The only time that script is being called is when we refresh the page. We'd like that countSongs script to be called when the remove button is clicked, and update the count within that span using ajax.


Solution

  • I figured it out by using the jquery .load() function instead of using ajax directly.

    It takes 3 files to accomplish this.

    1. The actual HTML document that displays the page (page-listen.php)
    2. The javascript file that houses all of my jPlayer js functions (demo.js)
    3. The html document that will run the code that is loaded with .load() (countthesongs.html)

    I'll post the important section of each document, with comments.


    page-listen.php (This span will act as the container that will display the number of songs that are currently in the users playlist.)

    <span id="count-songs-span">
      <script>
        var countSongs = JSON.parse(localStorage.playlist).length; // count the number of songs that are stored in localStorage key "playlist".
        document.write(countSongs); // print the number of songs
      </script>
    </span>
    

    When the page is first displayed, the number of songs that are in the playlist will be counted and shown to the user inside of the span called "count-songs-span".


    demo.js (These are the jPlayer functions that are doing the heavy lifting.)

      // Function to store the playlist in LocalStorage
        function updatePlaylist() {
          playlist = myPlaylist.playlist; // define playlist variable
          storage.set( 'playlist', playlist ); // store the playlist in localStorage as "playlist"
        }
    
      // Function to count the number of songs and print to the container
        function countTheSongs() {
        $( "#count-songs-span" ).load( "/js/jPlayer/countthesongs.html", function() {
            var theDiv = document.getElementById('count-songs-span'); // Assign the count-songs-span container we discussed earlier to a variable called theDiv
            theDiv.innerHTML = theDiv.innerHTML + countSongs; // Print the results of countthesongs.html using jquery .load() function
          });
      }
    
      // Function to remove an item from playlist
        $('.jp-playlist').on('click', '.jp-playlist-item-remove', function(){
          window.setTimeout(updatePlaylist, 500); // Store the playlist in localStorage with new number of songs, on a delay
          window.setTimeout(countTheSongs, 550); // Display the number of songs in the count-songs-span container
        });
    

    countthesongs.html (This is the HTML file that runs the short script to count the number of songs in the playlist.)

    <script>
      var countSongs = JSON.parse(localStorage.playlist).length;
    </script>
    

    So to make sense of these 3 documents, here's what's happening:

    1. A user removes a song from the playlist by clicking the remove button.
    2. The function to remove an item from playlist is fired, which stores the new number of items to localStorage (updatePlaylist()), then counts and prints that new number to it's container on the page (countTheSongs()).

    Using the .load() function, we're able to display the number of songs on the playlist as a user removes items, without the page reloading, just as it would if we would have used ajax.

    Hope this helps someone. Sorry if it's a little confusing.