I have use case of a form with an autocomplete that reads json from a backend, and also a set of input fields inside the form reading from state. I'm trying to make the page work as follows: 1- user clicks inside the autocomplete 2- user types text 3- user selects item 4- once clicked, entire form gets submitted to the backend 5- user gets redirected to the respective page
Here's my current amp code:
<form
className="amp-search-areas-form"
method="post"
// action-xhr={`${hostName}/api/areas`}
action-xhr="https://url/api/areas"
target="_top"
id="searchform"
dir="rtl"
>
<div
style={{
fontSize: 'large',
fontWeight: '600',
cursor: 'pointer',
paddingBottom: '10px',
textAlign: 'right',
}}
>
enter area name
</div>
<amp-autocomplete
filter="substring"
filter-value="name"
// src={`${hostName}/api/areas`}
src="https://url/api/areas"
on="select:AMP.setState({ defaultState: { area: event.value }}), searchform.submit"
query="name"
submit-on-enter="true"
highlight-user-entry="true"
items="items"
// on="change:searchform.submit" //triggers submit on select
// on="tap:search-lightbox.close,AMP.setState({ fullScreenLightBox: ['banner-search-panel'] })" //should close on change
>
<input
dir="rtl"
type="search"
name="selectedArea"
role="areasearch"
tabIndex="3"
className="amp-search-areas-input"
placeholder="placeholder"
/>
<AmpMustache
template={`
<div data-value="{{name}}">
<div>{{ name }}</div>
</div>`}
/>
</amp-autocomplete>
<input
name="typeField"
type="text"
// hidden
data-amp-bind-value="defaultState.type"
></input>
<input
name="catField"
type="text"
// hidden
data-amp-bind-value="defaultState.cat"
></input>
<input
name="areaField"
type="text"
// hidden
data-amp-bind-value="defaultState.area"
></input>
</form>
Of course I have imported all required amp components above the page, like form, bind, autocomplete, mustache, etc.
Here's my backend code:
exports.createSearchRedirect = async (req, res) => {
try {
console.log("exports.createSearchRedirect -> req.params", req.params)
console.log("exports.createSearchRedirect -> req.query", req.query)
console.log("exports.createSearchRedirect -> req.body", req.body)
let generatedUrl = '';
res.set(
'AMP-Redirect-To',
encodeURI('https://url/search/' + generatedUrl)
);
res.json(true);
} catch (error) {
console.log('exports.createSearchRedirect -> error', error);
}
};
My express config:
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
Okay, so I've solved it by changing the default encoding type to application/x-www-form-urlencoded
so my form now looks like this:
<form
className="amp-search-areas-form"
method="post"
action-xhr="url/api/areas"
target="_top"
id="searchform"
dir="rtl"
encType="application/x-www-form-urlencoded"> // this line here
.
.
.
etc
</form>