I am trying to write an application that will use an AJAX request to grab some JSON from a rails action. It seems like it works just fine, but when debugging I found that when I output the JSON value I need, it says that it is undefined.
Here's what I have currently:
Rails:
def complete
@case = Case.find(params[:case_id])
respond_to do |format|
format.html
format.json { render json: { :percentage => @case.complete } } ## Should produce something like {"percentage" => 0} and when I go to this url in my rails app I see that it does.
end
Javascript:
function updatePercentage(id_att, db_id, type) {
console.clear();
console.log("updatePercentage was called.");
$(".loading").progressbar({ value: false });
$.ajax({
type: "GET",
dataType: "json",
url: "/cases/" + db_id + "/" + type + "_complete.json", // e.g. /cases/42/type_complete.json
success: function(result) {
console.log("\n\nPercentage from AJAX is " + JSON.stringify(result.percentage));
}
});
}
When I go to localhost:3000/cases/XXXX/type_complete.json I see {"percentage":100} So obviously that's getting somewhere. But in the js console I just see "Percentage from AJAX is undefined."
When I say console.log("THE JSON OBJECT I'M GETTING BACK IS " + JSON.stringify(this));
The output is:
JSON: (In console)
{
"url": "/cases/980193955/type_complete.json",
"type": "GET",
"isLocal": false,
"global": true,
"processData": true,
"async": true,
"contentType": "application/x-www-form-urlencoded; charset=UTF-8",
"accepts": {
"*": "*/*",
"text": "text/plain",
"html": "text/html",
"xml": "application/xml, text/xml",
"json": "application/json, text/javascript",
"script": "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
"contents": {
"xml": {},
"html": {},
"json": {},
"script": {}
},
"responseFields": {
"xml": "responseXML",
"text": "responseText",
"json": "responseJSON"
},
"converters": {
"text html": true
},
"flatOptions": {
"url": true,
"context": true
},
"jsonp": "callback",
"dataType": "json",
"dataTypes": [
"text",
"json"
],
"crossDomain": false,
"hasContent": false
}
Why is this happening? And how do I fix it? As far as I can tell the JSON data should be there. But Javascript is acting like it's not.
thisin thesuccesscallback? You should provide a parameter to that callback, and use that instead ofthis. As you've already figured out,thisrefers to the promise returned by$.ajax