1

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!

2
  • Why not use res.json(JSON.stringify(result))? Commented Jul 10, 2016 at 14:12
  • @Aer0 i tried res.json as well, it won't work too. is this the right way of getting back success data? Commented Jul 10, 2016 at 14:27

3 Answers 3

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

sends not valid json.

Either use:

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

or

res.json(result);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.