Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do instant search with mongoosastic + AJAX?

I have configured mongoosastic successfully, I tried searching and it is working fine, but when it comes to front-end I'm not really sure on how to achieve this, I experimented with a lot of ways but couldn't come up with a good solution.

Here's the code.

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

So whenever I search something that is related to 'engineer', I will get a json data

enter image description here

So the backend does working perfectly.

However when it comes to jquery and ajax I keep getting bad request

The logic: whenever something is inserted then post that and find that result.

Here's the frontend jquery code.

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

    var search_term = $(this).val();


    $.ajax({
      type: "POST",
      url: "/api/search",
      success: function(){
        $('search_results').html(search_term);
      },
      error: function(data){
        alert('Error', data);
      }
    });

  });

HTML

<input type="text" class="form-control input-lg" id="search" name="search" placeholder="Search for part-time..." />



 <div id="search_results">


    </div>

How do I insert the json results to search_results?

like image 476
Jack Moscovi Avatar asked Nov 25 '15 10:11

Jack Moscovi


2 Answers

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);
    }
  });
});
like image 148
Val Avatar answered Sep 30 '22 04:09

Val


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!

like image 37
medee88 Avatar answered Sep 30 '22 04:09

medee88