Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jquery AJAX with node.js, handling the response from the server

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.

like image 543
ribsies Avatar asked Apr 14 '13 08:04

ribsies


1 Answers

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);
like image 82
brnrd Avatar answered Oct 07 '22 00:10

brnrd