Reputation: 565
I have setup a mongo database. For now I have just one id in my database. I am trying to fetch the data in my javascript file ( using ImpactJS engine ) with an ajax get request.
Below is how my database looks like for now. Its on mongo db. Very basic for testing purposes
{
"_id": "5303a4d4c4fd447a0a7fb528",
"__v": 0,
"ans": "ans",
"hint": "Hints.",
"score": 20,
"name": "ABC",
"pid": 1
}
I then use an Ajax request in my javascript file to fetch the "ans" field from the database. Below is my code for the same
getQuestionAnswer:function(){
var requestURL = "http://128.2.238.182:3000/problem?pid=".concat(this.passedQsId);
var answer;
$.ajax({
type:'GET',
url: requestURL,
async: false,
dataType: 'json',
cache: false,
success: function(data) {
answer = data.ans;
},
error: function(data) {
answer = "<p>ERROR</p>";
}
})
return answer;
},
The URL is passed correctly, I double checked it on my logs. However when I try to use this request function in my other function, i get infinte number of errors saying "NS ERROR FAILURE" or something. Below is the line of code where I get the error message
checkAnswer: function(id){
var correctAnswer = this.getQuestionAnswer();
}
Any help would be appreciated. I am totally new to javascript and web programming in general. This is kind of a challenge for me as I have mostly been coding in Java, C++!
Upvotes: 0
Views: 391
Reputation: 5226
Getting a little large for comments - here are some things to sort in the function
getQuestionAnswer:function(){
var requestURL = "http://128.2.238.182:3000/problem?pid=".concat(this.passedQsId);
var answer;
$.ajax({
type:'GET',
url: requestURL,
dataType: 'jsonp', /* different domains often require jsonp */
cache: false,
success: function(data) {
console.log(data); /* check */
answer = data.ans;
return answer; /* needs to be here */
},
error: function(xhr, status, error) {
console.log(xhr);
answer = "<p>ERROR</p>";
return answer; /* needs to be here *
}
});
/* ^ semi colon ending here */
/* return answer; */
/* removed - will not return the 'answer'
as the function is now Asynchronous */
},
Update: with example looking at the wider function and example callback
var answerfunctions = {
getQuestionAnswer : function(callback){ /* here accepts the callback function */
var requestURL = "http://128.,,etc";
var answer;
$.ajax({
type:'GET',
url: requestURL,
dataType: 'jsonp',
cache: false,
success: function(data) {
callback(data.ans);
},
error: function(xhr, status, error) {
console.log(xhr);
callback("ERROR");
}
});
}
};
/* call the function and pass a function as an argument to callback to */
answerfunctions.getQuestionAnswer(function(datareturn) { alert(datareturn); });
Upvotes: 1