我有一个AJAX调用来过滤用户搜索过的项目。此Ajax调用会在div中附加一些内容,包括提交按钮(和表单)以在收藏夹中添加该指定项目。此添加在过滤结果之前有效,但是当我使用AJAX进行过滤时,按钮不再起作用。它只是将我重定向到主页。
这是用于对结果进行排序的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) {
}
});
});
这是用于将项目添加到收藏夹的AJAX:
$(".test").change(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "get",
url: "{{ url('searchFilter') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
if(data.status == 'failedd'){
swal("Error!", "Error with filtering!", "error")
}
else{
$('.myDiv').empty();
$.each(data.idUser.matches, function(index, element) {
$('.myDiv').prepend('<div class="row" style="border:1px solid #b5b5b5;margin-bottom:20px">'+
'{!! Form::open(['class' => 'ajax-form', 'style' => 'float:right']) !!}'+
'<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">'+
'<input type="hidden" name = "idCampaign" id="idCampaign" value="'+element.attrs.sid+'">'+
'<button type="submit" id="test"><img align="right" src="{{ asset('/img/icon_add_fav.png')}}"></button>'+
'{!! Form::close() !!}</div>'});
}
},
error: function(data){
},
complete: function (data) {
}
});
});
修改
我发现当我过滤结果时,项目的ID不会改变。 Ajax只呈现一个id ...
答案 0 :(得分:0)
在函数中编写AJAX addFavorites代码。如下所示:
function insertFavorites()
{
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) {
}
});
return false;
}
用户点击提交按钮时调用该功能。如下所示
注意:已从&#34;提交&#34;更改了按钮类型到&#34;按钮&#34;
<button type="button" id="test"><img align="right" src="{{ asset('/img/icon_add_fav.png')}}" onclick="insertFavorites()"></button>
因为这类事件的Jquery .submit,.click,.changes在动态渲染字段中不起作用。
答案 1 :(得分:0)
尝试在我们的ajax调用之后放置return false;
,将停止提交导致重定向的表单。
另外,为什么你预先挂起整个div,为什么不在页面加载时渲染它但隐藏它,然后只是更新ajax成功的值,会给你更清晰的代码。