Reputation: 2640
I using self host api and want to use the data from the ajax call in another function, but it does not work. I get undefinded.
My Code:
function checkData() {
$.ajax({
type: "GET",
url: "http://localhost:8080/api/Data"
}).success(function (result) {
var datareturned = result.stateLog;
console.log('done' + datareturned);
x = datareturned;
test(x);
});
}
setInterval(checkData, 5000);
function test(data) {
alert(data); // Here i get undefined
}
Do you know how can I use the data?
Upvotes: 0
Views: 651
Reputation: 1294
Your result object does not seem to have a .stateLog property. If you are trying to access the html response status, you might want
.success(function (result, response) {
var datareturned = result;
console.log('done' + response);
x = datareturned;
test(x);
}
Or
.success(function (result, response, jqXHR) {
var datareturned = result;
console.log('done' + jqXHR.statusCode);
x = datareturned;
test(x);
}
Or something like that. If you try to return an Object as your result which ought to have a .stateLog property, then you should specify the dataType of the Ajax calls and/or make sure your server returns the correct format. e.g. if you return a json string, you need to parse it first before you can use it as an object. Of course the object then needs to have the desired property.
Upvotes: 0
Reputation: 2640
in the console.log it still comes undefined.
But if i change the code like that:
{
$.ajax({
type: "GET",
url: "http://localhost:8080/api/Data",
success: function (data) {
console.log(data);
}
});}
I get a console log (an object)
Upvotes: 0
Reputation: 319
I try this and Work fine:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/jquery-1.8.1.min.js"></script>
<script>
function checkData() {
$.ajax({
type: "GET",
url: "file.data.txt"
}).success(function (result) {
console.log('readed:' + JSON.stringify(result));
var datareturned = JSON.parse(result).stateLog;
console.log('done ' + datareturned);
var x = datareturned;
test(x);
});
}
setInterval(checkData, 5000);
function test(data) {
alert(data); // Here i get undefined
}
</script>
</head>
<body>
</body>
</html>
JSON DATA(file.data.txt):
{
"stateLog":"Active"
}
Upvotes: 1