What is the correct way to lengthy polls using jQuery and AJAX

I have a project that includes a live notification. So I came across using the io socket, but I did not have enough time to learn it. So I tried to do this using AJAX and jQuery. Below is my code structure, and I was wondering if this would work without any flaws?

setInterval(function(){
  if( !element.hasClass('processing') ){
    element.addClass('processing');
    $.ajax({
      type:         'post',
      dataType:     'json',
      url:      ajaxurl,
      data:         {},
      success:  function( response ){
        /* Success! */
        element.removeClass('processing');
      }
    });
  }
}, 2500);
+4
source share
2 answers

additional information

The way you described will work. From experience, I would just like to point out some things.

  • , ajax, .//, .

  • window.setTimeout() isActive.// , ,

  • , , , $.ajax(). , , ..

:

var isActive = true;

$().ready(function () {
    //EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
    //IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
    pollServer();
});

function pollServer()
{
    if (isActive)
    {
        window.setTimeout(function () {
            $.ajax({
                url: "...",
                type: "POST",
                success: function (result) {
                    //SUCCESS LOGIC
                    pollServer();
                },
                error: function () {
                    //ERROR HANDLING
                    pollServer();
                }});
        }, 2500);
    }
}

, , , . , - , .

+9

, : Jquery: Ajax: ?

, .

$("div.add_post a").click(function(){

  var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
            dlg.dialog("show");
  $.ajax({
        url : "/add.php",
        complete : function (){
            dlg.dialog("hide");
        }
     });
 return false;
});


//--Loading dialog

function loadingDialog(dOpts, text = " ,  ...")
{
    var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt=''/> "+text+"<div>").dialog(dOpts);
    $(".ui-dialog-titlebar").hide();

    return dialog;
}
0

All Articles