I have a function like this:
exports.saveAction = function (req, res) {
var conn = mysql.createConnection({
host : nconf.get("database:host"),
//port: 3306,
user : nconf.get("database:username"),
password : nconf.get("database:password"),
database : nconf.get("database:database"),
multipleStatements: true,
//ssl: 'Amazon RDS'
});
var action = req.body;
conn.query('UPDATE actions SET ? WHERE Id = ?',
[action, action.Id], function (err, result) {
conn.end();
if (err) throw err;
res.writeHead(200, { "Content-Type": "application/json" });
res.end("Updated Successfully");
});
};
and I am return "200", but it always returns in the error clause shown below:
$.ajax({
url: "/api/action/SaveAction",
type: "PUT",
data: ko.toJSON(self.stripDownObj()),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
if(result.status == 200){
self.isEditMode(!self.isEditMode());
}
},
error: function(result){
console.log(result);
}
});
Note: the sql query is successful and does save the data.
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });
ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.
It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success . success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
By returning JSON when you're expecting JSON
res.end('{"success" : "Updated Successfully", "status" : 200}');
and then
$.ajax({
....
datatype: "json", // expecting JSON to be returned
success: function (result) {
console.log(result);
if(result.status == 200){
self.isEditMode(!self.isEditMode());
}
},
error: function(result){
console.log(result);
}
});
In Node you could always use JSON.stringify to get valid JSON as well
var response = {
status : 200,
success : 'Updated Successfully'
}
res.end(JSON.stringify(response));
Express also supports doing
res.json({success : "Updated Successfully", status : 200});
where it will convert the object to JSON and pass the appropriate headers for you automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With