Ajax request back Undefined

Asked

Viewed 133 times

0

I am studying a little Ajax and testing your requisitions. My doubt is on account of the return, he is returning Undefined.

That is the function:

function recarregar()
{
    var jsonData = $.ajax({
        url: "http://xxxxxxx/o/Ano/1235",
        dataType: "text",
        method: "Post"
        async: false
    }).responseText;
    var teste = jsonData;
}


setInterval(recarregar(), 10000);

This is the return according to Postman

Uma imagem de um console mostrando o valor 152806

  • You don’t need to use async:false, use done or fail as shown in documentation : http://api.jquery.com/jquery.ajax/

1 answer

2

Note: Missing a comma between post" and async:

    method: "Post"
    async: false

Please DON’T USE async: false, this is obsolete and in the future browsers will remove this feature, this because the synchronized mode usually freezes the browser, different from asynchronous, as I explained in:

And as described in https://xhr.spec.whatwg.org/#Sync-Warning

Then change approach to use callbacks, to understand what callback is read this answer:

Then change setInterval to setTimeout, so it will only call the next one if the first one has been sent

function recarregar()
{
    $.ajax({
        url: "http://xxxxxxx/o/Ano/1235",
        dataType: "text",
        method: "POST"
    }).done(function (jsonData) {
         var teste = jsonData;
    }).always(function () {
         setTimeout(recarregar, 10000);
    });
}

Now about why you’re returning undefined must be due within the scope of the variables, to pass the access of the variable test you would have to either put it as global (in the scope of window.) and still add some kind of refresh in the specific DOM you want to change with the value, or else change the approach totally.

If you learn to use callbacks well you will probably be able to adjust everything, if you can indicate where you want to put the value of teste I can adjust the code and give you some suggestion.

  • I am only updating a number, it is on the front as a Label. then this my function would update this Label every x minutes

  • @Antonio_sistema_de_information has nothing to do with updating, nor with GET or POST, the problem is how the Xmlhttprequest API works and which in the future will no longer support async:false, because this is the same as asynchronous which is already something obsolete for a long time and the browsers will in the future remove, only making callback work for Ajax, ie your code in the future will fail if you continue to insist on using synchronized mode instead of asynchronized. Read the answer calmly and study the links I have indicated.

  • Thank you very much, I’m seeing the shared link and I’m understanding the error of the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.