Filter Hubspot Posts by Tag without changing pages (using Ajax and the search API)
Skip to content

Filter Hubspot Posts by Tag without changing pages (using Ajax and the search API)

I recently encountered a request for a module that could filter Hubspot blog posts without leaving the page the user is on (i.e. linking out to the specific tag url)

So I'm going to show you how to put together a very basic version of this using ajax and the search api:

1. Get your blogs tags

{% set my_tags = blog_tags("default", 250) %} 

2. Set up your tag dropdown 

 <select onchange="searchResults()" name="blog_tags" id="blog_tags">
{% for item in my_tags %}
<option value="{{item.name}}">{{ item.name }}</option>
{% endfor %}
</select>

Note here that on change we're calling the function searchResults that we'll create in step 4.

3. Create the area that will be populated by your function

<div id="search-results"></div>

4. Set up your search results function

 {%require_js %}
<script>
function searchResults() {
var selectedTag = document.getElementById('blog_tags').value;

$.ajax({
url: 'https://api.hubapi.com/contentsearch/v2/search?portalId={{ hub_id }}&domain={{request.domain}}&property=tag&term='+selectedTag,
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
let text = "";
const posts = json_result.results;
posts.forEach(printPosts);

document.getElementById('search-results').innerHTML = text;

function printPosts(item, index) {
text += index + ": <a href=\""+ item['url'] + "\">" + item['title'] + "</a><br>";
}
}
});
}
searchResults();
</script>
{%end_require_js %}

What this does is use ajax to call the search api. In our case we use "https://api.hubapi.com/contentsearch/v2/search?portalId=1951013&domain=www.seoanseo.ca&property=tag&term='+selectedTag"

Here I'm specifying the domain as the request domain, this prevents the api search other domains on your portal, you can remove it if you wish to search all your hubspot domains.

Then we use JSON to parse the data. Then we print it to our placeholder area (search-results')

In this simplified version we use item['url']  and item['title'] but the search api returns many more fields that you could play around with:

  • id
  • type
  • domain
  • featuredImageUrl
  • language
  • description
  • authorFullName
  • tags
  • publishedDate

You can see a quick demo of the module here