Submit Form after value update in Google AMP

835 Views Asked by At

Here i have sorting select box and i performed 2 events on change of select box, first set state of hidden value and second submit form.

I need to submit form with updated hidden value of sorting but, everytime i changed select box form can be submitted early then update hidden value.

So, I need delay on submit form or submit form after hidden value update.

Can you guide me how can i do this?

<amp-state id="sorting">
    <script type="application/json">
    { 
       "date_desc" : { "text" : "Most Recent", "type" : "desc", "by" : "date" },
       "year_asc" : { "text" : "Year Ascending", "type" : "asc", "by" : "year" },
       "year_desc" : { "text" : "Year Descending", "type" : "desc", "by" : "year" },
    }
    </script>
</amp-state>

<form target="_top" action="/amp/search" id="search" novalidate="" class="i-amphtml-form">
     <input value="desc" type="hidden" name="search[order_type]" [value]="sorting[sort || ''].type" id="search_order_type">
     <input value="top" type="hidden" name="search[order_by]" [value]="sorting[sort || ''].by" id="search_order_by">
</form

<select id="listing" name="listing" on="change:AMP.setState({sort:event.value}),search.submit">
    <option value="date_desc">Most Recent</option>
    <option value="year_asc">Year Ascending</option>
    <option value="year_desc">Year Descending</option>
</select>
1

There are 1 best solutions below

0
On

Instead of managing this state on the client side, it might be easier to send the <select> value to the server, then use the server code to extract the type and order from the <select> value.

// This is an express sample, but you could apply
// the concept to any server technology.

app.post('/amp/search', (req, res) => {
  /* ... */

  let type, by;
  if (req.body.listing === 'date_desc') {
    by = 'date';
    type = 'desc';
  } else if (req.body.listing === 'year_asc') {
    by = 'year';
    type = 'asc';
  } else if (req.body.listing === 'year_desc') {
    by = 'year';
    type = 'desc';
  } else {
    // error
  }
  
  /* render the sorted table response */
});
<form target="_top" action="/amp/search" id="search" novalidate="">
     <select id="listing" name="listing" on="change:search.submit">
         <option value="date_desc">Most Recent</option>
         <option value="year_asc">Year Ascending</option>
         <option value="year_desc">Year Descending</option>
     </select>
</form>

Does this fit your use case? Or was there something else you need in your form that this doesn't do?