I’m currently creating a small project and I want to prevent form from submit. That works well but I can’t give exact url to laravel route with ajax. How can do that?
Here is my code
<form id="sendlike" class="d-inline ms-5">
<input type="hidden" name="like" id="likeInput">
<input type="hidden" value="{{$amv->id}}" id="amvid">
<button class="btn btn-outline-primary" id="like">Like {{$amv->like}}</button>
</form>
Jquery
var like = document.getElementById("like");
var dislike = document.getElementById("dislike");
like.addEventListener("click", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var likecount = like.textContent;
var amvid = document.getElementById("amvid").value;
var addlike = parseInt(likecount.slice(5)) + 1;
document.getElementById("likeInput").value = addlike;
console.log("localhost:8000/amvtube/like/" + amvid)
// $("#sendlike").submit();
});
$("#sendlike").on("submit", function (e) {
e.preventDefault();
var likecount = like.textContent;
var amvid = document.getElementById("amvid").value;
var addlike = parseInt(likecount.slice(5)) + 1;
var likeData = addlike;
$.ajax({
type: "POST",
url: `{{ url('../../../../amvtube/like/'${amvid}') }}`,
data: likeData,
success: function () {
like.textContent = "Like" + addlike;
}
});
return false;
});
My route
Route::post('amvtube/like/{id}', [AmvController::class, 'like']);
Route function
public function like($id) {
$validator = validator(request()->all(), [
'like' => 'required',
]);
if($validator->fails()) {
return back()->withErrors($validator);
}
$amv = Amv::find($id);
$amv->like = request()->like;
$amv->update();
}
Please i need this TwT
2
Answers
First off all, give your route a name by adding this to your route:
Route::post('amvtube/like/{id}', [AmvController::class, 'like'])->name('amvtube.like');
Now in your jQuery, first create a variable called
url
. Then assign the url to it before passing it to your ajax. Here is the adjusted jQuery code.Now this way, it should work.
Please add "/" to route in route.php:
In JS: