PGrammer PGrammer - 1 month ago 4
Javascript Question

Jquery ajax when

I am using jquery when to wait until an ajax function is finished and then publish the results of the function in a test div. I am using an interval to repeat the process every 5 seconds. The results I am getting are undefined and then the id of the json element.

Here is my code.

shortWVCInterval = setInterval(defferedAjax, 5000);
GLB_VAR = "None";

function defferedAjax(){
$.when(checkAjax()).done(function(){
$('#test').append(GLB_VAR.id + " - ");
});
}

function checkAjax(){
var url = "https://jsonplaceholder.typicode.com/posts";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
success: function(data) {
GLB_VAR = data;
}
});
}


https://jsfiddle.net/Lh2q5c4t/

How do I get the Id on the first interval?

Answer

here the working code:

shortWVCInterval = setInterval(defferedAjax, 5000);
GLB_VAR = "None";

function defferedAjax(){
    $.when(checkAjax()).done(function(){
    $('#test').append(GLB_VAR.id + " - ");
  });
}

function checkAjax(){
     return $.ajax({
        type: "POST",
        url: "https://jsonplaceholder.typicode.com/posts",
        dataType: 'json',
    success: function(data) {
        GLB_VAR = data;
    }
});
}

https://jsfiddle.net/Lh2q5c4t/3/

Edit : you must add "return $.ajax", "The return statement stops the execution of a function and returns a value from that function."

Comments