I am trying to use LaravelShoppingCart with PNotify and I am a little lost and could use some pointers.
This is the interface I have so far:
When I click the yellow "add me" button, I spawn a new notification using PNotify on the top right, like you see in the picture.
What I want to do next is:
When I click the "add me" button, Cart::add()
would be called, and my class would be added to the cart session
The yellow button turns to "remove me", which would be able to call Cart::remove()
The notification persists on the top right corner (even if you go to another page. It's essentially referencing Cart::content()
), and when you click the "x" button on the notification, it would call Cart::remove()
as well.
I'm not really looking for code (although if it helps with explanation, feel free). I just simply want someone to explain to me how I could achieve this.
It seems like I need to use AJAX. If so, what do I need to add to my Laravel project for it to use AJAX to add to cart?
Not necessarily you need ajax. Every time you click "add me" button you just send a post request and add the class to your cart with Cart::add(). You display the added classes by listing the Cart::content(). Also you check in your view if the class is already added then change the button to remove class.
If you prefer ajax. then you just send a ajax call to your server with same process as mention. You don't have to add packages to your project to use ajax. you just need jquery plugin.
I prefer ajax because you don't have to load your page but it needs a lot of work.
Update
you need something like this.
$('#button').click(function(){
$.ajax({
type: 'post',
url: 'url',
data: {your: data},
dataType: 'json'
}).done(function(data){
//do something with your data
});
return false;
});
Note
In your ajax function. It should look like this if you submit the form.
$.ajax({
type: "post",
url: "{!! route('route') !!}",
data: $('#form').serialize(),
dataType: 'html'
}).done(function (data) {
but if your just passing selected data you need to pass the _token.
$.ajax({
type: "post",
url: "{!! route('route') !!}",
data: {data: value, _token: "{{ csrf_token() }}"},
dataType: 'html'
}).done(function (data) {
Update
Here is my sample code of my back-end.
public function addItem(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'field' => 'required'
]);
if ($validator->fails())
{
$data = Cart::content();
return view('errorview', compact('data'))->withErrors($validator);
}
Cart::add($data['id'], $data['name'], $data['qty'],
$data['amount']);
$data = Cart::content();
return view('myview', compact('data'));
}
Update
You need to add a class in all your buttons. something like this.
$('.btn').click(function () {
$.ajax({
type: 'post',
url: "{!! route('route') !!}",
data: {id: $(this).prop('id').substr(9), _token: "{{ csrf_token() }}"},
dataType: "html"
}).done(function (data) {
//more code here
});
return false;
});