Reputation: 181
I am making a phonegap app for android. I am receiving a json string and trying to parse it . It's a very small data.
{"result":{ "node":"32"}
}
if iam using alert(request.responseText)
the result is displayed but if i return this request.responseText to the calling function and collect it there in a variable like var x= somefunction(); x contains undefined.
var jsonObj = sendPostRequest(url,nurl);
console.log(jsonObj+""); // GIVES UNDEFINED HERE AT THIS LINE BUT SAME STATEMENT WORKS IN sendPostRequest()
if(jsonObj){
var Json = JSON.parse(jsonObj);
console.log(json);
document.getElementById("gnodei").innerHTML= json.result.wEventId;
}
I can collect this response in a variable y inside somefunction() but on returning this data to the calling function nothing reaches there. I use the above json data x just below it but it doesn't work.
please suggest.
edit: `function sendPostRequest(url,nurl){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0){
console.log(request.status);
//alert(request.responseText);
var txt= request.responseText;
console.log(txt);
return txt;
}
}
}
request.open("POST",url, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(nurl);
}`
The ajax call. Also there are multiple functions calling this ajax call after preparing their url and nurl values so i need this function as it is. I only need to know how to get back the response in my calling function. Thanks
Upvotes: 0
Views: 236
Reputation: 181
Solved it: Created a function to be passed as callback to the sendPostRequest(url,nurl) method. This callback is called only after the ajax call finishes as correct status. The callback function assigns the data that can be used thereafter.
Upvotes: 1