Skip to content

Instantly share code, notes, and snippets.

@besrabasant
Last active March 3, 2023 06:48
Show Gist options
  • Save besrabasant/4ea3c6503a1896e50b5c6973bc48395f to your computer and use it in GitHub Desktop.
Save besrabasant/4ea3c6503a1896e50b5c6973bc48395f to your computer and use it in GitHub Desktop.
Submitting Forms with Turbolinks ( tested with Laravel );
async submitForm() {
let $form = document.getElementById('form');
let formData = serialize($form); // Check resources for serialize() function
Turbolinks.controller.adapter.showProgressBarAfterDelay();
try {
let response = await fetch($form.getAttribute('action'), {
method: 'POST',
headers: {
'Accept': 'text/html, application/xhtml+xml',
'Turbolinks-Referrer': `${window.location.href}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData
});
let responseHtml = await response.text();
let location = response.headers.get('Turbolinks-Location');
let snapshot = Turbolinks.Snapshot.wrap(responseHtml);
if (!location) {
location = window.location.href;
}
Turbolinks.controller.cache.put(location, snapshot);
Turbolinks.visit(location, {action: 'restore'});
} catch (error) {
console.log(error)
} finally {
Turbolinks.controller.adapter.hideProgressBar();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment