Home > Software engineering >  how to redirect to another page if condition is not valid while using ajax?
how to redirect to another page if condition is not valid while using ajax?

Time:01-22

I want add product to the cart through ajax. only logged in user can add product to the the user. if user is not logged in redirect him to the log in page

Here are my ajax request in blade template

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    function addedToCart(){
        var product = $("#productId").val();;
        var val = $("#countItem").val();
        var unit = parseInt(val);
        $.ajax({
            type: "POST",
            url: "/addtocart",
            data: {product: product, unit: unit},
            dataType: "json",
            success: function (res){
                alertMsg.fire({
                    title: 'Product added to Cart'
           })
            }
        });
    }
     `

Here the controller code

function addToCart(Request $req){
    if($req->session()->has('user')){
        $cart = new Cart;
        $cart->user_id = $req->session()->get('user')['id'];
        $cart->product_id = $req->product;
        $cart->unit = $req->unit;
        $cart->save();
        return response($cart, 201);
    }
    
    else{
        return redirect('/login');
    }
    
}

It can not go the login route still remain in the same page

CodePudding user response:

Ajax request expects JSON Array Literals, such are JSON formatted array/objects and plain strings, in response. Meaning, you can't make redirect object return in PHP.

You can

// in controller
if (!$req->session()->has('user')) {
    return response()->json([
        'error' => "Forbidden"
    ], 403);
}

// save the cart and return success object

Then

// in JS
$.ajax({
    type: "POST",
    url: "/addtocart",
    data: {product: product, unit: unit},
    dataType: "json",
    success: function (res){
        alertMsg.fire({
            title: 'Product added to Cart'
        })
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
        window.location = 'path_for_guests'// this path should be returned from backend for greater security 
    } 
});

Also, be aware of not saved objects. For example, if $cart is not successfully saved you shouldn't return success message. Which is your code doing right now. To follow Object Calisthenics appropriate code (one else it too much), you can use switch and in suitable cases match for various exceptions and expectations like

  • user session doesn't exist 403
  • object not created 500
  • cart created 201
  • etc

CodePudding user response:

in JSON response you can not use redirect at server side.

either you can play with status here like if the user is logged in, then perform your action, otherwise return a response with status: false.

I have modified your code link below and I have added in comments on what I have changed.

Your JS code

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

function addedToCart(){
    var product = $("#productId").val();;
    var val = $("#countItem").val();
    var unit = parseInt(val);
    $.ajax({
        type: "POST",
        url: "/addtocart",
        data: {product: product, unit: unit},
        dataType: "json",
        success: function (response){
            if (response.status) { // if it is true
                alertMsg.fire({
                    title: 'Product added to Cart',
                });
            } else {
                // if it is false, redirect
                window.location.href = response.redirect_uri;
            }
        },
    });
}

Your controller function:

function addToCart(Request $request){
    if($req->session()->has('user')){
        $cart = new Cart;
        $cart->user_id = $request->session()->get('user')['id'];
        $cart->product_id = $request->product;
        $cart->unit = $request->unit;
        $cart->save();
        return response($cart, 201);
    }
    else{
        // you can return with status flag, and using the redirect_uri your can redirect at your desire page.
        return response()->json(array(
            'status' => false,
            'redirect_uri' => route('login'),
        ), 401);
    }
    
}

Not sure, about the false status you will get in the AJAX success(), if you will not get then you will have to add the error function after the success(). as we are passing header status in the response.

error: function (error) {
    // do console log to check what you get
}
  •  Tags:  
  • Related