I want to add something to database using Ajax. I have a link which submits the form and then Ajax call should work, but it's not. I use this same Ajax call on different page, but in that form I'm using simple button with type submit. But on this page, I want to submit with ...
This is the form
{!! Form::open(['id' => 'ajax-form', 'style' => 'float:right']) !!}
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idCampaign" id="idCampaign" value="{{$campaign->id}}">
<a class="fa fa-bookmark fa-2x" onclick="document.getElementById('ajax-form').submit();" aria-hidden="true" href="javascript:{}" style="color:#fd8809"></a>
{!! Form::close() !!}
This is the Ajax:
$("#ajax-form").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
if(data.status == 'failedd'){
swal("Error!", "You have already added this campaign to favorites! If you want to remove it, go to your Favorites list page", "error")
}
else{
swal("Success!", "You added the campaign "+ data.idCampaign + " to favorites!", "success")
}
},
error: function(data){
swal("Error!", "error")
},
complete: function (data) {
}
});
});
When I click on this link, it redirects me to another page which throws: MethodNotAllowedHttpException.
Change your ajax url to this:
url: '/addFavorites',
and your route to this:
Route::post('/addFavorites', 'SearchController@addFavorites');
Just to make sure you point at the same url
EDIT:
make sure that you have one route with get and the same route with post. see bellow:
Route::get('/addFavorites', 'SearchController@loadFavorites'); <-to load the page
Route::post('/addFavorites', 'SearchController@submitFavorites'); <-to submit the data
Change this: $("#ajax-form").submit(function(event) {
To this: $('#yourid').click(function(){
Remove the onclick in the 'a' element and add the id='yourid' with the name you want.
MethodNotAllowedHttpException usually comes when you haven't defined route or you have defined route for get method and you are using the route for post method. please check your routes.php