I have a for each loop that outputs notes along with upvotes/downvotes that share a relationship with the notes, it works fine but I can have a lot of these forms being dynamically recreated, The only way I can use ajax to post a specific form is by foreach looping the Ajax script along with the form, so that the id's of the form in the ajax script are unique.
I'd like to remove the bloat from the Ajax script and just use a single request to post the data, but I can't figure out how to post a specific form without using unique ID's.
@foreach ($getNotesAll as $getnotes)
<p class="notes">{{$getnotes->body}}</p>
<?php $formRand = rand(); ?>
<form class="vote-form" id="upvote-form{{$formRand}}" method="post"
action="/notes/vote">
<button type="submit" form="upvote-form{{$formRand}}" id="vote-up{{$formRand}}"
class="vote-btn upvote"></button>
<input type="hidden" name="type" value="1">
<input type="hidden" name="voteid" value="{{$_SESSION['user_id']}}">
<input type="hidden" name="noteUniqueID" value="{{$getnotes->noteUnique}}">
<input type="hidden" name="noteid" value="{{$getnotes->user_id}}">
{{csrf_field()}}
</form>
<form class="vote-form" id="downvote-form{{$formRand}}" method="post"
action="/notes/vote">
<button type="submit" form="downvote-form{{$formRand}}" id="vote-
down{{$formRand}}" class="vote-btn"></button>
<input type="hidden" name="type" value="0">
<input type="hidden" name="voteid" value="{{$_SESSION['user_id']}}">
<input type="hidden" name="noteid" value="{{$getnotes->user_id}}">
<input type="hidden" name="noteUniqueID" value="{{$getnotes->noteUnique}}">
{{csrf_field()}}
</form>
<?php
echo "<script>
$( '#downvote-form". $formRand . "' ).on( 'submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/notes/vote',
data: $(this).serialize(),
success: function( msg ) {
}
});
});
$( '#upvote-form".$formRand."' ).on( 'submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/notes/vote',
data: $(this).serialize(),
success: function( msg ) {";
}
});
});"; ?>
@endforeach
I've tried something along the lines of this
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: '/notes/vote',
data: $(this).serialize(),
success: function () {
location.reload();
}
});
e.preventDefault();
});
});
But that just posts all the forms on the page when clicking a single button, I've tried adding a unique onclick event for the forms but I've had the same result. Any guidance would be appreciated
input type="text" readonly, or add it to a constant variable (const token_$1where $1 is the step in the iteration) in your javascript snippet. If choosing the latter approach, add this info to the form data before submitting the form.