0

I know it looks like a duplicate question and believe me, I read all of them and tried everything, but I can't get this to work (JQuery 1.11.0):

function gip(){
var ccode;
$.ajax({
 url: 'http://freegeoip.net/json/?callback=?',
 dataType: 'json',
 crossDomain: true,
 async: false,
 success: function (data) {
 alert(data.country_code);
 ccode = data.country_code;
 },
 error: function(error) {
 alert(error)
 return '';
 }
 });
alert(ccode);
return ccode;
}

No matter what I do, alert(ccode) fires before alert(data.country_code) so my return value is undefined. Unfortunately my knowledge is limited, and I can't see how I can do what I need in asynchronous mode. I simply need to return data.country_code.

asked Mar 18, 2014 at 16:54
1
  • The simple answer is, never use async:false. Don't wait for asynchronous operations to complete, use the response handlers they provide to respond to them. Commented Mar 18, 2014 at 16:59

2 Answers 2

3

First of all, since you are using jsonp, you can't do anything :(

As of version 1.8, async:false is no longer supported

You'll need to wait for success handler to get whatever value you are looking for.

answered Mar 18, 2014 at 16:57
Sign up to request clarification or add additional context in comments.

11 Comments

async: false is supported in 1.11 and 2.x and is NOT deprecated yet. Even if he downgraded to 1.5, he wouldn't be able to send a synchronous jsonp request because it's jsonp, not because the library doesn't support it. It simply isn't possible due to how a jsonp request works.
What was deprecated in 1.8 was the use of .done() .fail() and .always() with synchronous requests.
I really didn't see jsonp.
@KevinB, I thought you would argue, that I stole your answer.
No, I care more that the answers available are correct. My answer is common knowledge
|
3

It is not possible to send a synchronous jsonp request.

JSONP requests are done by appending a <script> tag to the <head> tag. Since it isn't possible to force a <script> tag to load synchronously after the DOM is ready, it isn't possible to force a jQuery jsonp request to be synchronous.

answered Mar 18, 2014 at 17:57

1 Comment

hmm... if you created an iframe with a document and added the script tag to it before it gets parsed, would it load that script synchronously? Still wouldn't solve the OP's issue, but it would technically cause a synchronous jsonp request to happen.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.