I am trying to send JSON from Express.js back to client but I can't make it work.
routes/editor.js
exports.save = function(req, res){
fs.readFile(__dirname + "/../public/index.html", function (err, data) {
if (data == oldhash) {
res.json({ r: 'no' })
}
else {
res.json({ r: 'yes'})
}
});
});
public/javascript/test.js
$( ".save" ).click(function( event ) {
event.preventDefault();
$.ajax( {
url: 'http://localhost:3000/save',
data: r,
type: 'GET',
success: function(r) {
if( r == 'yes' ) {
$('#echoResult').append('<p>yes</p>');
}
else {
$('#echoResult').append('<p>no</p>');
}
}
});
});
And then accordingly which is the response from the server, append the right HTML.
What am I missing here? All the AJAX examples I saw, they didn't help too much.
Any suggestions would be more than welcome.
Edit
I get this Error on client-> Uncaught ReferenceError: r is not defined
The client error can be resolved like this:
$( ".save" ).click(function( event ) {
event.preventDefault();
$.ajax( {
url: 'http://localhost:3000/save',
type: 'GET',
success: function(data) {
if( data.r == 'yes' ) {
$('#echoResult').append('<p>yes</p>');
}
else {
$('#echoResult').append('<p>no</p>');
}
}
});
});
The data attribute is in the success callback with r as parameter.
Without more details about how you are using express I can't say much about the server code.