Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 343
jmogera Avatar asked Apr 02 '14 19:04

jmogera


People also ask

How do I return data after Ajax call success?

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); });

Why is Ajax success not working?

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.

What does Ajax request return?

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.


1 Answers

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.

like image 139
adeneo Avatar answered Sep 25 '22 06:09

adeneo