0

I am just learning ajax and have used short polling to reload a div every 0.5 second to display new data. How do I change this to long polling? I know web sockets would be a better approach but for now i want to use ajax.

function load_messages(){
    $.ajax({
        url: '{% url 'msgs_json' %}',
        datatype: 'json',
        type: 'GET',
        success: function(body) {
            body.forEach(function(b) {
                if (b.fields.is_read === false){
                    console.log("unread message(s)")
                    $("#inbox").load(location.href + " #inbox");
                    $("#outbox").load(location.href + " #outbox");
                }
            });
        }
    });
}

$(document).ready(function(){
    setInterval(load_messages,500);
});
Asef Hossini
  • 655
  • 8
  • 11
Efaz
  • 284
  • 2
  • 12
  • Why was this closed? The duplicate asks what the difference is and this question asks how to implement long polling. – D. Pardal Jul 12 '20 at 16:58
  • 1
    It can still be considered "real-time" with a longer delay on the interval. It's up to you. ... On a separate note, you should consider putting logic to allow the previous ajax request to finish (or timeout, if thats the case) before calling the same request again. Especially with such a short interval. – GetSet Jul 12 '20 at 16:59
  • @D.Pardal True long polling requires server side modifications also as explained in the alternate answer. It's not even known what stack OP is using to do that. If you have something substantively different will gladly re-open – charlietfl Jul 12 '20 at 17:00

0 Answers0