Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trigger pjax request upon JS form submit #201

Open
omzy opened this issue Mar 26, 2019 · 2 comments
Open

Trigger pjax request upon JS form submit #201

omzy opened this issue Mar 26, 2019 · 2 comments

Comments

@omzy
Copy link

omzy commented Mar 26, 2019

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?

@omzy
Copy link
Author

omzy commented Mar 26, 2019

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?

@mbuzun
Copy link

mbuzun commented Oct 24, 2019

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 }));
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants