Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to refresh div

I have some elements in my page and I need to refresh their contents every 5 seconds. The code that I'm going to show you works well but it looks so long and repeating itself. When I use only setInterval function, page doesn't loaded regularly before the interval comes. Can you suggest a better way to do this? Thanks in advance. Here is my code:

var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");
$.ajax({
    url: "song.php",
    success: function (response) {
        var nowPlaying=$.parseJSON(response);
        $song.html(nowPlaying.song);
        $album.html(nowPlaying.album);
        $cover.css("background-image", "url("+nowPlaying.cover+")");
        $background.css("background-image", "url("+nowPlaying.cover+")");
    }
})
var refreshSongDetails=setInterval(function() {
    $.ajax({
        url: "song.php",
        success: function (response) {
            var nowPlaying=$.parseJSON(response);
            $song.html(nowPlaying.song);
            $album.html(nowPlaying.album);
            $cover.css("background-image", "url("+nowPlaying.cover+")");
            $background.css("background-image", "url("+nowPlaying.cover+")");
        }
    })
}, 5000);
like image 862
Guney Cobanoglu Avatar asked May 12 '15 15:05

Guney Cobanoglu


1 Answers

Create your ajax call into a function and call it :

var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");

function ajaxCall() {
  $.ajax({
      url: "song.php",
      success: function (response) {
          var nowPlaying=$.parseJSON(response);
          $song.html(nowPlaying.song);
          $album.html(nowPlaying.album);
          $cover.css("background-image", "url("+nowPlaying.cover+")");
          $background.css("background-image", "url("+nowPlaying.cover+")");
      }
  })
}

ajaxCall();

var refreshSongDetails = setInterval(ajaxCall, 5000);
like image 167
R3tep Avatar answered Oct 12 '22 14:10

R3tep