Pass parameter "q" to instantsearch search box

Hi, I am building a website with Hugo and I want to use instantsearch on it. I have managed to create a search page which shows all results and filters by search. I want to use an external search input in every other page and send the users to the search page with this input.

What I would like is the search results page to appear already filtered by the search input parameter. I already create a page like (https://url/search/q=query) but the results page isn’t taking the parameter.

How can I achieve this?
THANKS!

You’re really close! All you need is to add synchronization between the URL parameters and your instantsearch.js instance.

You’ll find information about how to achieve this in https://www.algolia.com/doc/guides/building-search-ui/going-further/routing-urls/js/.

tl;dr you should be able to add routing: true to your instantsearch.js initialization and have your setup working directly.

Hi thanks for you answer, unfortunately that doesn’t solve the issue in my side. Let me explain my case again. I have an input form with search parameter that creates a URL sort of like this one:

BaseURL/search/?q=ux

Then I have (on a different page) the search results page and the instant search implementation.

I would like the results page to be filtered by whatever is after the query parameter when I search from something in any page.

This is my search setup, note that I am trying to add something that reads from the url and passes it to the search box but unsuccessfully :

// Adding a query paramater.
var url_string = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search; //window.location.href
var url = new URL(url_string);
var q = url.searchParams.get("q"); 


const searchClient = algoliasearch('XXX', 'XXX');

const search = instantsearch({
  searchClient: searchClient,
  indexName: 'XXXX_XXXX',
  routing: true,
  searchParameters: {
    query: q,    
  }
});

search.addWidget(
  instantsearch.widgets.searchBox({
    container: '#searchbox',
    placeholder: 'Búsqueda',
    autofocus: false,
    searchAsYouType: true,
    searchParameters: {
    query: q,    
  }
  })
);


search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      empty: 'No se han encontrado resultados',
      // https://caniuse.com/#feat=template-literals
      item: '<div class="my-3"><h3><a href="{{ permalink }}">{{{ _highlightResult.title.value }}}</a></h3><small class="text-muted">{{ summary }}</small></div>'
    },
    transformData: {
      item: function(data) {
        data.lastmod_date = new Date(data.lastmod*1000).toISOString().slice(0,10)
        // https://caniuse.com/#search=MAP
        const tags = data.tags.map(function(value) {
          return value.toLowerCase().replace(' ', '-')
        })
        data.tags_text = tags.join(', ')
        return data
      }
    }
  })
);



search.addWidget(
  instantsearch.widgets.stats({
    container: "#stats",
    templates: {
      body(hit) {
        return `<span role="img" aria-label="emoji">⚡️</span> <strong>${hit.nbHits}</strong> resultados encontrados ${
          hit.query != "" ? `for <strong>"${hit.query}"</strong>` : ``
        } in <strong>${hit.processingTimeMS}ms</strong>`;
      }
    }
  })
);

search.addWidgets([
  instantsearch.widgets.refinementList({
    container: document.querySelector('#filtros'),
    attribute: 'categorias',
  })
]);

search.addWidgets([
  instantsearch.widgets.refinementList({
    container: document.querySelector('#tagcloud'),
    attribute: 'etiquetas',
  })
]);


search.addWidget(
  instantsearch.widgets.pagination({
    container: '#pagination',
    maxPages: 20,
    // default is to scroll to 'body', here we disable this behavior
    scrollTo: false
  })
);

search.start();

Hi @ux1, could you create a codesandbox to demonstrate your issue? I still think the solution from jerksa should work, if I understand your issue correctly. We have starter templates here.

Hi Cindy,

I have my website live where you can see what’s happening.

Try to load that URL and you’ll see the behaviour I am commenting about. That page should throw some results for “ux” as I understand, but for now it’s not filtering the results.

If you need access to the repository of code let me know. I already shared my search.js file with the instantsearch configuration. I must be doing something really wrong for it not to work. I have checked the correct order of the scripts, and the console is not showing any errors, at this point I am lost for a solution.

Thanks,
JB

you’re adding this code to the page:

const search = instantsearch({
  searchClient: searchClient,
  indexName: 'test_TELETRABAJOS',
  routing: true,
  searchParameters: {
    query: q,    
  }
});

but searchParameters no longer exists, and instead you can use stateMapping:

instantsearch({
  searchClient: searchClient,
  indexName: 'test_TELETRABAJOS',
  routing: {
    stateMapping: {
      stateToRoute: function (uiState) {
        return {
          q: uiState['test_TELETRABAJOS'].query,
        };
      },
      routeToState: function (routeState) {
        return {
          test_TELETRABAJOS: {
            query: routeState.q,
          },
        };
      },
    },
  },
});

This means you don’t need to extract q manually @ux1

hope that helps!

hi,

I can confirm this solution works and now everything works as expected.

Thanks!