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
.
答案 0 :(得分:1)
将您的ajax网址更改为:
url: '/addFavorites',
以及您的途径:
Route::post('/addFavorites', 'SearchController@addFavorites');
只是为了确保你指向同一个网址
编辑:
确保您有一条获取的路线和发布的相同路线。见吼:
路由:: get(&#39; / addFavorites&#39;,&#39; SearchController @ loadFavorites&#39;); &lt; -to加载页面
Route :: post(&#39; / addFavorites&#39;,&#39; SearchController @ submitFavorites&#39;); &lt; -to提交数据
更改此内容:$("#ajax-form").submit(function(event) {
对此:$('#yourid').click(function(){
删除&#39; a&#39;中的onclick。元素并使用您想要的名称添加id='yourid'
。
答案 1 :(得分:0)
MethodNotAllowedHttpException通常在您没有定义路线或您已为get方法定义路线并且您正在使用路线方法时出现。请检查你的routes.php