I am a newbie to Ajax, I am trying to fetch data from using Ajax Cross domain functionality. Ajax function is being called from test.php which calls the stats.php to request data
Stats.php
<?php
$data = array();
$data[0]=1;
$data[1]=1;
echo json_encode($data);
?>
Test.php
<html>
<head>
<script src="./lib/jquery.min.js"></script>
<script>
var var0=0;
$(document).ready(setInterval(function() {
$.ajax({
cache: false,
type: "GET",
url: "http://10.0.0.2/dashBoard/stats.php",
data: "",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
success: function(data){
console.log(window.var0 = data[0]);
}
});
}, 1000));
$(document).ready(setInterval(function()
{
document.getElementById("p1").innerHTML = window.var0;
},1000));
</script>
</head>
<body>
<p id="p1"></p>
</body>
</html>
test.php is in 10.0.0.1 stats.php is in 10.0.0.2
Ajax is able to call stats.php and i can see the response json but i am not able to use this response data in test.php. I am not able to assign data[0] value which is 1 according to stats.php to window.var0 in test.php which is a global variable. However this works perfectly fine when stats.php is in 10.0.0.1 along with test.php but my requirement is to load data from stats.php in 10.0.0.2.
Please help.
Thanks in advance.
Your problem is you decoupled the function that brings the data from the server and the function that takes that data and changes the DOM based on the server response. Furthermore, you are executing both functions at the same time. This means the function that changes the DOM will fire before the response from server comes back.
The main purpose of using an $ajax is to know when the response has come back, so you could use that data. By placing $.ajax in a function and what you do with the response in another, you break this "wait for data to come" behavior. The whole purpose of the success function is that it executes when the response has returned successfully. In success you already have the data. So use it to change DOM directly:
Use this instead:
$(document).ready(setInterval(function() {
$.ajax({
cache: false,
type: "GET",
url: "http://10.0.0.2/dashBoard/stats.php",
data: "",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
success: function(data){
document.getElementById("p1").innerHTML = data[0];
}
});
}, 1000));
I can't be sure, since I don't know the context, but most likely, you can safely remove the timeout wrapper now. There's no point in delaying the call for data, right?
var var0;
function updateP1(){
document.getElementById("p1").innerHTML = var0;
}
$(document).ready(function() {
$.ajax({
cache: false,
type: "GET",
url: "http://10.0.0.2/dashBoard/stats.php",
data: "",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
success: function (data) {
var0 = data[0];
updateP1();
}
});
});