This seems like an incredibly simple issue but I have no idea why I’m getting undefined. I’m using jQuery to fetch data off a PHP script – specifically a string which the PHP file echoes. Here’s the code:
<script type="text/javascript">
var map1;
$.get("script.php", function(data)
{
map1 = data;
});
alert(map1);
</script>
Now if I alert(map1), it ends up being undefined… why exactly is this the case? I thought by declaring map1 outside $.get, it would fix the problem but that’s not the case. If I alert(map1) inside the $.get function, it ends up fine and the variable holds a string (as opposed to being undefined). So the question is… what’s going on with map1? And how can I stop it from being undefined / going out of scope / whatever is happening to it?
Thanks in advance.
As @Michael has put, the
.getcall is asynchronous so your javascript is executing this call, and then carrying on with your script, which is why you get anundefinedalert box.Your best option is to put in a
successcall: