Louis.L
Louis.L

Reputation: 13

Express js - How to get response from ajax call?

I am trying to send form data to server side using ajax (sending a username), and in the server side perform SQL query and pass back the result to my template (EJS).

In my server side (ajaxTest.js)

router.post('/', function(req, res){
console.log(req.body);
var query = connection.query("select * from account where username='" + req.body.username+ "'",function  (err,result) {
    console.log(query.sql);
    if (err)   {
        console.error(err);
        return;
    }
    console.error(result);

    res.send("Result "+JSON.stringify(result));
});

});

In my template (ajaxTest.ejs)

$(document).ready(function  () {
$("#submit").on("submit",function  (e) {
    e.preventDefault();
    data = {};
    data.username = 'user101'; 
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        url: 'http://localhost:3000/ajaxtest',
        success: function(data) {
            console.log('success');
            console.log(JSON.stringify(data));
        }
    });
})

});

In the above code, result is successfully logged onto my console, but the 'success' and data does not get returned. Is there a reason why result is not being sent back to the template (ajaxTest.ejs)?

I'd greatly appreciate any feedback on the situation!

Upvotes: 1

Views: 8106

Answers (3)

Iceman
Iceman

Reputation: 6145

res.send("Result "+JSON.stringify(result));

sends not valid json.

Either use:

res.send(JSON.stringify(result));

or

res.json(result);

Upvotes: 2

Alongkorn
Alongkorn

Reputation: 4197

Your front-end expects json data. Your back end should returned corresponding data too.

on your node.js, please change the return line from

res.send("Result "+JSON.stringify(result));

to

res.status(201).json(result); // return status 201, and json data (do not stringify)

Upvotes: 0

enRaiser
enRaiser

Reputation: 2636

Its because you are corrupting the syntax of JSON by prepending it with 'Result'.

 res.send("Result "+JSON.stringify(result));

Instead do simple

res.send(JSON.stringify(result));

Upvotes: 1

Related Questions