-1

I want to change the value of a variable. I tried the following method but it does not work:

    function MapData() {
      var  bbs=0 ;
        $.ajax({
            url: "/admin/subfactors/BBth",
            type: "GET",
            success: function (result) {
                bbs = result;
               }
            }
        });
        return bbs;
    };
  • What exactly do you want to change? – Static Aug 03 '20 at 18:54
  • _...change the value of a variable...._ What variable? What change? You have to be a bit more specific. So what do you want to achieve and what doesn't work with your code? – B001ᛦ Aug 03 '20 at 18:55
  • @B001 I think he wanted to change the variable **"bbs"** value – Fritzdultimate Aug 03 '20 at 18:56
  • 1
    Duplicate: Check this https://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success – Velu S Gautam Aug 03 '20 at 19:01
  • 1
    Does this answer your question? [jQuery: Return data after ajax call success](https://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – Velu S Gautam Aug 03 '20 at 19:02
  • My Ajax returns a float that shows when alerted. I want the value of the returned number to be equal to the value of the bbs. – amir barghi Aug 04 '20 at 07:13

2 Answers2

2

$.ajax is asynchronous, so you need to wait for it to complete:

async function MapData() {
    var  bbs=0 ;
    bbs = await $.ajax({
        url: "/admin/subfactors/BBth",
        type: "GET",
    });
    return bbs;
});

and then when you call it:

let bbs = await MapData()
dave
  • 62,300
  • 5
  • 72
  • 93
1

You need to use callbacks (or some other way to handle async behavior) (your ajax request is async, and therefore your return is happening before the request completes.

function MapData(cb) {
$.ajax({
    url: "/admin/subfactors/BBth",
    type: "GET",
    success: function (result) {
        cb(result)
       }
    }
});

function cb(result) {
    console.log(result)
}

MapData(cb)
user2263572
  • 5,435
  • 5
  • 35
  • 57