Juliette
Juliette

Reputation: 4439

Variable is not updating after ajax request

I have the code below which is in a Vue script.

user_id = 100; //sample data

$.ajax({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    type: "GET",
    url: '/user',
    success: function (user) {
        user_id = user.user_id;
        console.log(user_id); //returns 1
    },
    error: function (result) {
    }
});

console.log(user_id); //returns 100 not 1

I want to be able to store the value that is resulted from the ajax request which is 1. However, when I console.log at the end of the script it returns 100 not 1. I think that I need to use a promise/callback to solve this but I am not sure how/what I need to do. Can someone help me?

Upvotes: 1

Views: 596

Answers (2)

Zam Abdul Vahid
Zam Abdul Vahid

Reputation: 2721

Define your method and return as a promise.

function getUsers() {
  return new Promise((resolve, reject) => {
      $.ajax({
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: "GET",
        url: '/user',
        success: function (data) {
            resolve(data);
        },
        error: function (error) {
            reject(error);
        }
     });
  });
}

You would call the method as below.

getUsers().then((data) => {
    console.log(data); /* you will get the new data returned from ajax.*/
}).catch((error) => {
    console.log(error);
});

Upvotes: 2

junvar
junvar

Reputation: 11604

This is how you can promisify callbacks in general:

let doXWithCallback = callback => {
  // do x...
  callback();
};

let doXPromisified = () => new Promise(doXWithCallback);

doXWithCallback(() => console.log('do x with callback'));
doXPromisified().then(() => console.log('do x promisified'));

For your example specifically:

let doRequest = () =>
        new Promise((resolve, reject) =>
                $.ajax({
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    type: "GET",
                    url: '/user',
                    success: user => resolve(user.user_id),
                    error: reject(),
                }));

doRequest.then(userId => console.log('userId is', userId));

Upvotes: 1

Related Questions