Hello, I’m trying to figure out how this blog search might be put together:
Basically, after typing your search query, the blog index page should display the articles including the search query.
Hello, I’m trying to figure out how this blog search might be put together:
Basically, after typing your search query, the blog index page should display the articles including the search query.
Hi @GabrielPerte,
this can be done via AJAX. So basically you’ll need to clone and modify the search module. I think @piersg has done something like that in the past
best,
Anton
Gabriel messaged me directly but to help others, I think searching on keyup would work e.g.
const input = document.getElementById('blog-search-input');
input.onkeyup = (e) => {
let input_val = this.value;
const listSelector = documents.getElementsByClassName('blog-listing-wrapper')[0]; // whatever div wraps your blog listings
if (input_val.length > 0) {
let request = new XMLHttpRequest();
request.open('GET', "https://api.hubapi.com/contentsearch/v2/search?portalId=[PORTAL ID]&term="+input_val+"&type=BLOG_POST&length=SHORT", true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
let data = JSON.parse(this.response);
let results = data.results;
let amount = results.length;
if (results === undefined || results.length == 0) {
listSelector.innerHTML = "";
listSelector.innerHTML += "<p style='margin: 0 auto;'>Sorry, there are no results for that search. Please search something else.</p>"
} else {
results = Array.from(results);
results.forEach(node => {
let date = node.publishedDate;
let tag = node.tags[0];
// structure this html for each result however you structure your blog listings normally
listSelector.innerHTML += "<div class='post-item content-item'><div class='img-wrapper mb-20 blog-featured-image-wrapper blog-search-image'><a href="+ node.url + " class='hs-featured-image-link'><img src="+ node.featuredImageUrl + "></a></div><p id='hubspot-topic_data'>" + tag + "</a> | " + date + "</p><div class='post-header blog-title'><h3 class='h5'><a href="+ node.url + " >"+ node.title + "</a></h3></div><div class=' blog-body clearfix'><p>"+ node.description + "</p></div></div></div>"
});
}
} else {
// We reached our target server, but it returned an error
console.log(this.response);
listSelector.innerHTML = "";
listSelector.innerHTML += "<p style='margin: 0 auto;'>Sorry, there was an error</p>"
}
};
request.onerror = function(status, error) {
console.log(error);
};
request.send();
}
}