0

I have been trying to learn Javascript/jQuery but I have hit a wall that I can't seem to break. This is my code:

function beginProblem() {
var myVar = getMyVar();
console.log(myVar);
}

function getMyVar(){
$.ajax({
    url: "myTest.php",
    success: function(result){
        var myVar = result;
        //  return myVar;   THIS DOESN'T WORK
    }
});
return myVar; //    This doesn't work either
}

beginProblem();

myVar is logging as undefined because the console.log runs before getMyVar is complete. I have read some other questions about this issue but I wasn't managed to understand the solution, can someone enlight me, what should I keep in mind when I need to obtain a variable from a ajax call and only then execute the rest of the function?

Sorry and thanks in advance!

csharp_ant
  • 75
  • 1
  • 10

3 Answers3

0

So in ajax method you point url to "myTest.php". Check this url again. If you're using Chrome right-click choose Inspect element(or press F12, if you're using Firefox you can download and install Firebug plugin to debug) before run, click on "Network" tab, and see your request in raw format. If your request return code 200, it's mean url is ok, unless check it. If code is 200, check your function again.

In case, it return code 500, check your function again, return type, logic sequence. And 400, it means it can find your services, your must check your url with fully path. I don't have enough knowledge with PHP. But I'm experienced in Java, if you change to java, do as my direction.

Phong Nguyen
  • 277
  • 4
  • 16
0

try some like this

function beginProblem() {
var myVar = getMyVar({
  success:function(result)
  {
    console.log(result);
  }
});
}

function getMyVar(obj){
$.ajax({
    url: "myTest.php",
    success: obj.success
});
}

beginProblem();
0

Try this, it'll work....

function beginProblem() {
var myVar = getMyVar();
console.log(myVar);
}

function getMyVar(){
$.ajax({
    url: "myTest.php",
    async: false,
    success: function(result){
         return  result; 
    }
});
    }

beginProblem();