I’ve made a simple JS which retrives data from my servlet. Data which I’m receving are two random numbers. I want to print this values every 3 seconds.
<html>
<head>
<button onclick="getP()">Try it</button>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var arr = new Array();
var url = "http://10.10.1.19:8080/examples/MyHelloWorld";
function getPos() {
var jqxhr = $.getJSON(url+"?getpos&callback=?",
function(data) {
//alert("success x " + data.x + ", y: " + data.y);
arr[0] = data.x;
arr[1] = data.y;
})
.success(function(data) {
//alert("second success x " + data.x + ", y: " + data.y);
})
.error(function() { alert("error"); })
.complete(function(data) { });
}
function onUpdate(){
pos = getPos();
document.write("On Update: success x: " + arr[0] + ", y: " + arr[1] + "<br>");
}
function getP(){
setInterval("onUpdate()", 3000);
}
</script>
</head>
Everything almost work fine, but at the begining I dont receive that values – here is output:
On Update: success x: undefined, y: undefined
On Update: success x: undefined, y: undefined
On Update: success x: 84366016, y: 1675639473
On Update: success x: 87449458, y: 139664776
On Update: success x: 980514625, y: 902346893
On Update: success x: -1435971236, y: -156758443
On Update: success x: -2095036525, y: -973261813
On Update: success x: -1304285873, y: 1260988577
On Update: success x: -1056490280, y: 1080724495
On Update: success x: -51836505, y: -706315772
On Update: success x: -358732800, y: -1112197198
On Update: success x: -638049254, y: 565725784
On Update: success x: -550065549, y: -851319836
On Update: success x: -2091397055, y: -1486304337
On Update: success x: -394112078, y: 671840086
On Update: success x: -1462169807, y: -567576336
On Update: success x: 2138172836, y: 1437950295
On Update: success x: -517824901, y: 1736496095
On Update: success x: -1129327909, y: 2010537838
On Update: success x: 1331271573, y: 1572909584
On Update: success x: -316422252, y: -2019877720
On Update: success x: 532846139, y: -1840296395
On Update: success x: -355252412, y: -866851861
On Update: success x: -276365039, y: 616559691
and so on…
Question is – why first two lines has “undefined” word insted of value? In my conosole in Chrome I can observe “200 OK” response on two first (and rest of) getJSON requests. Maybe I messed up with some values ? Thx in advance for any help.
This is happening because you are dealing with asynchronous code. Your document.write line is executing before the Ajax request completes. You have some problems in your code too.
getPos()doesn’t return nothing, so why are you assigning its return to “pos”? Put the code that must be executed after the request completes in the callback. mplungjan already rewrote your code in his answer.