-1

I've been trying for hours to get this to work, but it's just not budging; I have the following code:

var text = "";
function getText(c1, c2)
{
    url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=" + c1 + "-" + c2 + "_relations&prop=revisions&rvprop=content"
    $.ajax({
         type: "GET",
         dataType: "jsonp",
         async: false,
         url: url,
         success: function (data) {
                var obj = (data.query.pages );
                var keys = [];
                for(var k in obj) keys.push(k);
                if (keys[0] == -1) { 
                    //Link doesnt exist
                    text = "-1";            
                    return text;
                }
                //Link Exists
                else {
                        link = "http://en.wikipedia.org/wiki/" + c1 + "-" + c2 + "_relations"
                        text = c1 + "-" + c2 + " Relations"                     
                        return text;
                }
            }

    });
    return text;
}   

var a = (getText(country1, country2))
alert(text);
alert(a);

I'm making an ajax request; a simple inquiry to see if wiki has a page between any 2 given countrie. If I use alert inside, it works fine, and it returns the correct data inside the text variable. However, when the getText function is called outside, the text variable is always empty. I've tried everything I can think of, including getting the app to sleep for some time, but even that didn't work. I know the async doesn't work from ajax 1.8 onwards, but is there anyway around this?

Thanks in advance.

tj56
  • 162
  • 3
  • 12
  • 4
    `1)` Do not use `async: false`... ever `2)` Any problems, see `1)`. please learn how to use async ajax calls (or Ajax promises) :) – iCollect.it Ltd Jun 24 '14 at 08:34

1 Answers1

1

It is because the asynchronous behavior of ajax. You can't return values from ajax like this way. Because the function will not wait for the success event to happen.

When you put an alert inside that function, success event may occur before the user clicks on alert. That is why it returning value. Otherwise it will not return the value.

Its not a good practice to use async : false in ajax calls. It will freeze the browser.

Good practice is to call a method from the ajax success with the returned data, then do operations with that data inside the function.

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53