How to return success from ajax post in Node.js

27,860

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.

Share:
27,860
jmogera
Author by

jmogera

Updated on August 05, 2022

Comments

  • jmogera
    jmogera almost 2 years

    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.