0

I'm trying to set a variable from a ajax call that runs a function. The code below returns imgurlthumbvar in the console log put the alert(test) says it's undefined. I did some research and found out that the it has something to do with AJAX being asynchronous. Could anyone please help. Thanks in advance!

        function displayimg(id2){
        $.ajax({
        url:'getphotos.php',
        type:'POST',
        dataType: "JSON",
        data:{id2:id2},
        success: function(result){
            $.each(result, function(){
                imgurlvar = this.imgurl;
                imgurlthumbvar = this.imgurlthumb;
                console.log(imgurlthumbvar)
                //console.log('test')
                return imgurlthumbvar 
            })
        }
        });
    }

    $('#test123').click(function(){
        var test = displayimg(7)
        alert(test)
    })
AdamGIS
  • 25
  • 5

1 Answers1

0

Try

function displayimg(id2) {
    return $.ajax({
        url: 'getphotos.php',
        type: 'POST',
        dataType: "JSON",
        data: {
            id2: id2
        }
    });
}
// AJAX returns a promise


$('#test123').click(async function(){
    var result = await displayimg(7); // result is AJAX response
    var test;
    $.each(result, function(){
        imgurlvar = this.imgurl;
        imgurlthumbvar = this.imgurlthumb;
        console.log(imgurlthumbvar)
        //console.log('test')
        test = imgurlthumbvar 
    })

    alert(test)
});

await makes an asynchronus call look and behave like synchronous but without actually making it synchronous (sync. calls are discouraged due to UI freezing issue

Vinay
  • 7,442
  • 6
  • 25
  • 48