0

I'm trying to get back query data in JSON from my serverside code running on Node.JS

Here is my clientside AJAX request:

$(function() {
  var values = $(this).serialize();
  $.ajax({
    url: '/querySearch',
    type: 'post',
    data: values,
    success: function(msg){
      console.log(msg);
    },
    error: function(){
      alert('failure');
    }
  });
});

My serserside code:

app.post('/querySearch', function(req, res) {
  var queryNumber = Number(req.body.queryNumber);
  if (queryNumber == 1){
    executeQuery1(res, sendQueryResults);
  }
  else if (queryNumber == 4){
    executeQuery4(res, sendQueryResults);
  }
  else if (queryNumber == 6){
    executeQuery6(res, sendQueryResults);
  }
  else if (queryNumber == 7){
    executeQuery7(res, sendQueryResults);
  }
});

function executeQuery1(res, callback) {
    var query = "" +
    'query string';
    service.oneshotSearch(query, {}, function(err, results) {
      if (err) {
        console.log(err);
        alert("An error occurred with the search");
        return;
      }
    callback(res, results);
    });
  });

} 

function sendQueryResults(res, results) {
  res.json(JSON.stringify(results));
  res.end();
}

However, at the moment, my webpage won't even finish loading. What am I doing wrong?

4
  • what is happening? What is firebug/devtools saying when you make a request? Are there any server side errors? Commented Jul 17, 2013 at 17:21
  • Can you post code for sendQueryResults ? Commented Jul 17, 2013 at 17:26
  • The POST request isn't getting a response back. I've updated my post with more code above. Commented Jul 17, 2013 at 17:51
  • What are the values? What is supposed to happen with the response if queryNumber is something else than 1,4,6,7; what in case of an err in the search? Commented Jul 17, 2013 at 17:55

2 Answers 2

1

You need to call res.end() after your have written your data in.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, one issue I see might be a problem is that res.json accepts an object and you're passing a string. Try:

res.json(results);

or just res.send:

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

or I think this would work as well

res.send(results);

All three shouldh have the same result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.