How to use functions with jQuery (solved)

How to use functions with jQuery (solved)
0

#1

I am trying to complete the local weather app using the ipinfo API.
I access the city,country and coordinates likeso

<script src="https://code.jquery.com/jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
	$.get("http://ipinfo.io" ,function(data){
		console.log(data.city+' '+data.country);
		console.log(data.loc);
	},"jsonp");
});
The output comes correctly with the city,country and coordinates. Now I am trying to write the same as above using functions
<script src="https://code.jquery.com/jquery.js" type="text/javascript"></script>
<script>
function getCityCountry() {
	var cityCountry=''
	$.get("http://ipinfo.io" ,function(data){
		cityCountry=data;
	},"jsonp");
	return cityCountry.city+' '+cityCountry.country
}

function getLocation() {
	var location=''
	$.get("http://ipinfo.io" ,function(data){
		location=data;
	},"jsonp");
	return location.loc;
}

$(document).ready(function(){
	$.get("http://ipinfo.io" ,function(data){
		console.log(getCityCountry());
		console.log(getLocation());
	},"jsonp");
});

</script>

Now the output comes as undefined for all the above mentioned value.
What am I doing wrong?What is the correct way to define and use functions in jQuery?


#2

The issue is that $.get() is an asynchronous function and you are trying to return the variable before it receives any result. Basically the code requests some data and then jumps to the next operation before the data arrives and ends up returning an empty variable.

You could use a synchronous ajax request and get exactly what you tried there but i’m not quite sure if it’s a good idea.
Source: http://stackoverflow.com/questions/6685249/jquery-performing-synchronous-ajax-requests


#3

Look at your first example you have console.log inside your request and it logs the data to the console
in your functions eg getCitycountry() put a console in and get rid of the return … do the same for getLocation
then in your document ready function you try and do a get request with console.log of the functions which you created for doing the get request
get rid of that whole block … every thing … just have
$(document).ready(function(){
getLocation();
getCityCountry();
});
you should now see your data in console

now to get the data to the html page … I just quickly put this together as im at work but it shows the basics of adding the info to your html page
its not going to show when you run it here click edit on codepen to see it work