pjax
pjax copied to clipboard
Trigger pjax request upon JS form submit
I have activated pjax on a form as follows:
var pjax = new Pjax({
elements: "#search-form",
selectors: [".search-results"]
});
Now within my form I have an hidden input field. I have a dropdown outside of the form which can set the value of this hidden input dynamically. So for example I have:
<select id="sort-by">
<option value="name">Name</option>
<option value="size">Size</option>
</select>
<form action="/search" method="post" id="search-form">
<input type="hidden" id="sort-by-value" name="sort-by" value="">
<button type="submit">Submit</button>
</form>
JS:
$('#sort-by').change(function() {
var value = $(this).val();
$('#sort-by-value').val(value);
$('#search-form').submit();
});
As you can see, I am submitting the form when the dropdown value changes, but this results in a non-pjax request. How can I make it trigger the pjax request when I submit the form via JS?
OK I found a solution. Instead of triggering a form submit event, trigger a click on the submit button in the form:
$('#search-form button').click();
Whilst this now works, I still think it would be more elegant to trigger a form submit event. Is this something that can be looked in to?
You can try something like this
function pjaxFormSubmit(form) {
if (typeof(Event) !== 'function') { // IE 11 fallback
document.querySelector(`${form}`).submit();
}
document.querySelector(`${form}`).dispatchEvent(new Event('submit', { cancelable: true }));
}