Harshit Bisht Harshit Bisht - 5 months ago 8
Javascript Question

MeteorJS.On refreshing a page the search results get lost

I am using a searchbox for my webapp.On clicking the search button the user gets directed to the 'searchresults' page and the results are displayed.But on refreshing the page the search results are lost.How can I recover them using session?
The HTML code is:

<div class="form-group">
<input type="text" class="form-control" id='searchbox' placeholder="Search">
</div>


The js code is:

Template.navigation.events({
'submit form':function(event){
event.preventDefault();
var searchbox=document.getElementById('searchbox').value;
Router.go('/posts/search/'+searchbox);
}
});

Template.searchresults.helpers({
'post':function(){
var searchbox=document.getElementById('searchbox').value;
var search=new RegExp('\\b'+searchbox+'\\b','i');
return Posts.find({name:search});
}
});


and routerjs code is:

Router.route('/posts/search/:somesearch/',{
template:'searchresults',
name:'searchresults',


});

Answer

Instead of using a helper function, let's set the data context in your route:

Router.route('/posts/search/:somesearch/',{
  template:'searchresults',
  name:'searchresults',
  data: function(){
    return Posts.find({ name: this.params.somesearch });
  } 
});

Remove your post template helper entirely.

In your HTML template you'll need to iterate with {{#each this}} as this will be the cursor returned by the data function in the router.

Note, for multi-word searches and special characters you'll need to url-encode/decode the search string.