jmogera
jmogera

Reputation: 1759

How to return success from ajax post in Node.js

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.

Upvotes: 17

Views: 29860

Answers (1)

adeneo
adeneo

Reputation: 318352

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.

Upvotes: 37

Related Questions