1

Please would someone help me to update a global variable (user_ID) with the response from an AJAX request.

I have attempted the following with no success - https://newbedev.com/jquery-storing-ajax-response-into-global-variable. Alert() has consistently stated global var was undefined,

Note the console.log() message states a valid user_ID in the inner-scope. I just need to get it out..

Thanks :-)

// update global variable (user_ID) with ajax response

var user_ID;  // empty var to be populated with result
function receiveUserId(layerURL) {
    $.ajax({
        url: layerURL,
        crossDomain: true,
        type:"GET",
        // process the response from the server
        success: function(result){
            user_ID = result.user_ID; //JSON obj.prop
            console.log("The server responded with the following user ID: ", user_ID)
            return user_ID
            }
        });
}
taylort139
  • 11
  • 2
  • The problem is not with setting the value, that part works. The problem is because the AJAX call is asynchronous and you need to work with the callback/promise pattern correctly, which will in turn allow you to remove the global variable as it's bad practice to use them. See the duplicate for more information. – Rory McCrossan Sep 10 '21 at 08:39
  • 2
    Also the site you link to is giving terrible advice there - never use `async: false` as a workaround for this problem. – Rory McCrossan Sep 10 '21 at 08:40
  • Maybe this article could help: https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7 – Lea Sep 10 '21 at 08:50

0 Answers0