Home > Software engineering >  Is there a way to create 'add to cart' in ecommerce website without refreshing the page?
Is there a way to create 'add to cart' in ecommerce website without refreshing the page?

Time:10-10

Hi my fellow problem solvers. Hopefully you have a productive day. I am working on a e-commerce website project where by I do it by using Laravel 8. So far I have reached a point to create 'add to cart' so as customers could do a shopping. By reading different tutorials i am grateful that I can add products to cart, edit and update them also deleting. But I want it to work without refreshing the page. I used Jquery to create Ajax request as a lot of tutorials suggested. I think it will be simple for you to understand and help if i will show my codes.

here is my 'add to cart' link

<li class="add_to_cart"><a href="javascript:void(0)" data-tippy="Add to cart" onclick="addtocart(<?php echo $product->productID ?>)" data-tippy-placement="top" data-tippy-arrow="true" data-tippy-inertia="true"> <span class="lnr lnr-cart"></span></a></li>

Here is Ajax and Jquery

<script type="text/javascript">

$.ajaxSetup({
    headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
 });
    
function quickview(id) {
        
    $.get('/quickview/' id, function (response) {
        if (response) {
            $("#id").html(response.id);
            $("#brand").html(response.brand);
            $("#productname").html(response.product_name);
            $("#price").html(response.price);
            $("#description").html(response.product_context);
            $("#img").attr('src',response.image);
        }
    })
}

function addtocart(id) {
    var _url = '/product/add-to-cart/' id;

    $.ajax({
        url: _url,
        method: "GET",
        data: {
            _token: '{{ csrf_token() }}', 
            id: id
        },
        success: function (response) {
            window.location.reload();
            // I think here is where I stuck,
        },
        error: function (data) {
            console.log('Error:', data);
        }
    });           
}
</script>

Here is my route

Route::get('/product/add-to-cart/{id}', [ProductController::class, 'addToCart'])->name('add.to.cart')->middleware('loggedin');

Here is controller

public function addToCart($id)
{
    $product = Product::findOrFail($id);
    $cart = session()->get('cart', []);
    
    if(isset($cart[$id])) {
        $cart[$id]['quantity']  ;
    } else {
        $cart[$id] = [
                     "name" => $product->product_name,
                     "quantity" => 1,
                     "price" => $product->price,
                     "maelezo" => $product->product_context,
                     "image" => $product->image
         ];
    }
       
    session()->put('cart', $cart);

    return response()->json(['success' => true]);

    // return response()->json($cart);
    //return response()->json($cart);
}

CodePudding user response:

The simplest solution for this would be removing href attribute from anchor tag.

<li class="add_to_cart">
  <a data-tippy="Add to cart" onclick="addtocart(<?php echo $product->productID ?>)" data-tippy-placement="top" data-tippy-arrow="true" data-tippy-inertia="true"> 
    <span class="lnr lnr-cart"></span>
  </a>
</li>

Other solution would be changing anchor tag with buttons or, a simple span {custom designed button}.

<button onclick="addtocart(<?php echo $product->productID ?>)">add to cart </button>

Adding button inside form or input type='submit' will submit the form so be aware of that.

How it works

function showmsg1(){
  document.getElementById("msg").innerText = 'hello, you clicked button without refresh';
}

function showmsg2(){
  document.getElementById("msg").innerText = 'hello, you clicked button now it will refresh, this is hell...!';
}
<h1> hello, wassup</h1>

<h3> click on buttons </h3>

<span> Without refresh: </span> <a onclick="showmsg1()"> <button>click me</button></a><br/>

<span> With refresh: </span><a onclick="showmsg2()" href=""> <button> click me </button> </a><br/>

<span id="msg"></span>

CodePudding user response:

Answering in accordance with your comment on my previous answer.

Working example here

Sample HTML

    Click on buttons<br/>
    
    <span>Item btn1  <button onclick="addtocart(this)" class="btn btn-primary" id="btn1" value="btn1">Add to/Remove from cart</button></span><br/><br/>
    <span>Item btn2  <button onclick="addtocart(this)" class="btn btn-primary" id="btn2" value="btn2">Add to/Remove from cart</button></span><br/><br/>
    <span>Item btn3  <button onclick="addtocart(this)" class="btn btn-primary" id="btn3" value="btn3">Add to/Remove from cart</button></span><br/><br/>
    <span>Item btn4  <button onclick="addtocart(this)" class="btn btn-primary" id="btn4" value="btn4">Add to/Remove from cart</button></span><br/><br/>
    <span>Item btn5  <button onclick="addtocart(this)" class="btn btn-primary" id="btn5" value="btn5">Add to/Remove from cart</button></span><br/><br/>
    <div id="sessions"></div>

Script

//Laoding the dynamic page on document ready
$(document).ready(function(){
  $("#sessions").load("showSession.php");
});
//function to add to cart 
function addtocart(e){
  val = e.value;
  $.post("sessions.php",{type: "addtocart", value : val},function(data, status){
    if(status == "success"){
      $("#sessions").load("showSession.php");//Laoding the dynamic page once added/removed
    }
  });
}

For any queries comment down.

  • Related