How to do instant search with mongoosastic + AJAX?

偶尔善良 提交于 2019-12-01 05:49:16

What you need to do is

  1. on every key stroke, get the input value
  2. send it via Ajax to your backend
  3. use the JSON you get back upon success (here we just display "title: salary" it in the div)

So your front-end code would look like this:

$('#search').keyup(function() {

  // 1. grab the search term from the input field
  var search_term = $(this).val();

  // 2. send it to your back-end via ajax in the body 
  $.ajax({
    method: "POST",
    url: "/api/search",            // <-- your back-end endpoint
    data: "search=" + search_term  // <-- what you're sending
    dataType: "json",              // <-- what you're expecting back
    success: function(json){       // <-- do something with the JSON you get
      // 3. parse the JSON and display the results
      var res = json.hits.hits.map(function(hit) {
          return hit._source.title + ": " + hit._source.salary;
      });
      $('search_results').html(res.join("<br />"));
    },
    error: function(data){
      alert('Error', data);
    }
  });
});

I'm working on something very similar to this right now. First, it looks like you are missing parameters in your initial ajax request, so your node server is not getting any information:

$('#search').keyup(function() {
//Perform the ajax request
var search_term = $(this).val();
$.ajax({
  type: "POST",
  url: "/api/search",
  data: {"search": search_term},
  success: function(data) {
     //Loop over all the data and output it, appending data to element
     //with a line break
     for(var i=0; i < data.hits.length; i++)
    $('search_results').append(data.hits[i]._source.title+'<br />');
  },
  error: function(data){
    alert('Error', data);
  }
});

});

When debugging these issues it has been very helpful for me to use console.log() in my node server if you have access to it to see what data it is actually getting:

// For the Search API
router.post('/api/search/', function(req, res, next) {
  console.log("%j", req.body.search)
  Job.search(
    {
      query_string:
      { query: req.body.search }
    } , function(err, results) {
        if (err) return next(err);
        res.json(results);
    });
});

The log will very clearly report undefined or the correct string that you are expecting, so that way you can see if your parameters are correct

You may also want to check you node server address and port (just as a sanity check). For my ajax requests I have to put

url: "http://localhost:9200/api/search" 

in front of my queries simply because my server is on a different port

Here's some more information about the jQuery post function for your reference:

http://api.jquery.com/jquery.post/

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!