Search code examples
jqueryajaxvariablestransfer

Jquery get value of a variable from a ajax-call and put it to a new function


im having problem with getting value of a variable from the ajax-call function getRequest and put it into function test, not sure how it works, any help is appreciated!

function test() {
    var out = getRequest().name; //problem
    console.log(out);
};
function getRequest() {
    $.ajax({
        url: '/nextdocument',
        type: 'GET',
        async: true,
        cache: false,
        timeout: 11000, //vänta på svar från servern om ingen inläsning
        success: function(data) {
            var name = data.description;
            var price = data.price;
            console.log("read--> " + name + price);
            setTimeout(
                    'getRequest()',
                    1000
            );

        }
    })
}

Solution

  • function test() {
        var XHR = getRequest();
        XHR.done(function(data) {
           var out = data.description;
           console.log(out);
        });
    }
    
    function getRequest() {
        var XHR = $.ajax({
            url: '/nextdocument',
            type: 'GET',
            async: true,
            cache: false,
            timeout: 11000, //vänta på svar från servern om ingen inläsning
            setTimeout(getRequest, 1000);  //WHY
        });
        return XHR;
    }