this is my first time posting a question on here, I've mostly just been a lurker creeping on other questions, but this is something I've been trying to figure out and for the life of me can't.
Basically what I'm doing is using AJAX from the client side to hop over to the server, run some code that searches an external API which gives me some data, then I need that data to come back to the client. Here is my code... this is all using node.js with express
Client side
$('#search').click(function(){
$.ajax({
type: "GET",
url: "/search",
dataType: "json"
}).done (function (data) {
alert(data);
});
});
Server side
app.get('/search', function(req, res){
factual.get('/t/places',{q:'starbucks'}, function (error, data) {
console.log(data);
res.send(data);
});
});
Now I know that when the #search button is clicked, it does go over to the server and successfully runs that code. But I do not know how to get that data off of the server and back into the client to work with it there.
I found other posts that mention things like, res.send/res.write/res.end, I've tried every form of those to my knowledge and I can never seem to get that data back to the client.
Any tips or possibly better ways to do this would be very much appreciated.
Try the following code server side:
app.get('/search', function(req, res){
factual.get('/t/places',{q:'starbucks'}, function (error, data) {
console.log(data);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
});
It should work. The code client side looks ok.
Edit: You can use also :
res.json(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With