Reputation: 337
I made a module in node.js. Basically, this module grabs data from mongodb and returns a JSON value.
Now in Express.js, the front-end developer (not me) is using a jQuery plugin to do things. This jQuery needs a JSON variable as a parameter to do its thing.
Now, I have no idea how to send my JSON variable (which is generated server-side), to the jQuery plugin, which works client-side. I can't wrap my head around how to start doing this, so I'm having a hard time googling for it. No idea what the keywords will be. So, both technical answers and a general explanation of how this work will be appreciated.
Upvotes: 1
Views: 61
Reputation: 21629
Try the following code:
Client side jQuery:
$.ajax({
type: 'POST',
url: 'http://localhost:3000/request',
data: {
test: "test"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(result){
alert(result);
},
error : function(){
console.log("error")
}
});
In Node.js
Try the following server side code to handle /request
:
app.get('/request', function(req, res){
var data = {'TestKey':'TestValue'};
//For test at server side only
console.log('Sent this data to client:\n' + JSON.stringify(data));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
res.writeHead..
& res.end..
res.json(data);
Upvotes: 1