my requirement of coding is "when i am click on wishlist heart icon. if i am not login, then i am going to login page & If i am login then fa-fa heart color is change orange when i am added item in wishlist & grey when it remove. i am sending json response refer my coding.
controller:
public function add_to_wishlist(Request $req)
{
$userId=Session::get('userid');
if(empty($userId))
{
return response()->json(['status'=> 1]);
}
else
{
$checkWishlist=DB::select('select * from wishlist where user_id=? && product_id=?',[$userId,$req->sub_id]);
if($checkWishlist)
{
DB::table('wishlist')->where('user_id',$userId)->where('product_id',$req->sub_id)->delete();
return response()->json(['status'=> 2]);
}
else
{
DB::table('wishlist')->insert(['user_id'=>$userId,'product_id'=>$req->sub_id]);
return response()->json(['status'=> 3]);
}
}
}
blade code:
<input type="text" name="status" id="status" class="form-control status" value="">
<a class="sub" data-id="{{$value->sub_id}}" href="#"><i class="fa fa-heart" style="float:right;color:grey"></i></a>
jquery and ajax:
<script type="text/javascript">
$(document).ready(function(){
$('.sub').click(function(e) {
var sub_id=$(this).attr('data-id');
var input=$(this).prev();
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/add-to-wishlist') }}",
method: 'get',
data: {
sub_id: sub_id,
},
success: function(result){
input.val(result.status);
}});
});
});
</script>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…