Search code examples
jqueryajaxnode.jselasticsearchmongoosastic

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?


Solution

  • 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);
        }
      });
    });