I'm having a follow button on the front end it allows you to save an entry to a specific section (type: channel) and it's all working great, but i need to achieve this with AJAX
This is my Form
{% if currentUser %}
<form id="followForm" method="post" accept-charset="UTF-8">
{{ csrfInput() }}
{{ actionInput('entries/save-entry') }}
{{ hiddenInput('sectionId', sectionID) }}
{{ hiddenInput('enabled', '1') }}
{{ hiddenInput('title', followTitle ) }}
{{ hiddenInput('fields[followerName]', currentUser.username ) }}
{{ hiddenInput('fields[relatedUserId]', currentUser.id ) }}
{% if followItem is defined %}
{{ hiddenInput('fields[relatedEntryId]', followItem.id ) }}
{{ hiddenInput('fields[relatedSectionTitle]', followItem.section ) }}
{% else %}
{{ hiddenInput('fields[relatedEntryId]', entry.id ) }}
{{ hiddenInput('fields[relatedSectionTitle]', entry.section ) }}
{% endif %}
<button id="followBtn" type="submit">Follow</button>
</form>
{% endif %}
What i've tried:
$('#followForm').submit(function(ev) {
ev.preventDefault();
$.ajax({
type: 'POST',
url: 'entries/save-entry',
dataType: 'json',
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
});
so it seems there is something wrong with my JS, since it's continue to submit the form as default form and reloading the entire page instead of using Ajax.
any ideas would be great, Thanks
DOMContentLoaded
event? It's possible the#followForm
element doesn't exist yet when the code is executed. Try opening the debugger in the devtools and putting a breakpoint in the line with$('#followForm')
to see if and what the selector finds.$('#card{{followId}}').load(' #card{{followId}} > *');
where{% set followId = loop.index %}
but it still refresh the entire page. should i post another question or is it okay here ?