Reputation: 93
I have a set of posts which are loaded into the page using foreach, and utilises the paginate function with Laravel so I can infinite scroll through the post. Each post has a unique form, the first posts which aren't loaded with js scroll submit fine using ajax, however the posts that are loaded in using JScroll, don't seem to work with ajax, it just loads the forms action rather than the form returning false.
Ajax form post
$(function () {
$('.vote-btn').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/notes/vote',
data: $(this).parent('form').serialize(),
success: function () {
}
});
});
});
Jscroll
$(function() {
$('.notes-content-con').jscroll({
autoTrigger: true,
loadingHtml: '<img src="{{URL::asset("images/ellipsis.gif")}}" alt="Loading" class="paginate-load" />',
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.notes-content',
callback: function() {
$('ul.pagination:visible:first').hide();
}
});
});
<div class="notes-content-con">
@foreach ($notes as $note)
<div class="notes-content">
<p>{{$notes->body}}</p>
<form action="/vote" method="post" id="vote-form">
<input type="submit" class="vote-btn">
<input type="hidden" name="note-id" value="{{$note->id}}">
</form>
</div>
@endforeach
</div>
It seems to be because the posts are being inserted after page load, the ajax post doesn't pick it up so the form submit on the loaded posts just go straight to the action. I've tried inserting the ajax into the callback function, but that just creates duplicate post requests which is pointless, I've tried reloading the ajax script which had the same results. A fix would be appreciated because I can't find anything regarding this.
Upvotes: 0
Views: 425
Reputation: 744
Change your click function to this
$(function () {
$('body').on('click', '.vote-btn', function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
type: 'post',
url: '/notes/vote',
data: $this.parent('form').serialize(),
success: function () {
}
});
});
});
This will allow the jQuery to bind the click event to elements that are loaded after the initial page load. You could use another element besides body
that is a closer relative to the forms you're trying to submit to reduce run time as long as the element is on the page on the initial load and won't be removed.
Upvotes: 2