Home > OS >  Javascript Redirect Modal in Laravel
Javascript Redirect Modal in Laravel

Time:07-17

When the user likes a story on the card, users saves it with the "save" button. I do this as a savePost in my .js file. But if the user is not registered I am redirecting as "location.replace(APP_URL "/login")".

I want to redirect to a modal on the homepage instead of /login. Is it possible for me to do this as a session or something?

function savePost(t) {
    $.ajaxSetup({
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
        }
    });
    $(this);
    $.ajax({
        url: APP_URL   "/save_favorite",
        type: "POST",
        dataType: "json",
        data: {
            item: t,
            _token: $('meta[name="csrf-token"]').attr("content")
        },
        success: function(e) {
            1 == e.bool ? $("#save-icon-"   t).removeClass("text-muted").addClass("icon-filled") : 0 == e.bool && $("#save-icon-"   t).removeClass("icon-filled").addClass("text-muted")
        },
        error: function(e) {
            location.replace(APP_URL   "/login")
        }
    })
}

CodePudding user response:

Your current JS:

 function savePost(t) {
        $.ajaxSetup({
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
            }
        });
        $(this);
        $.ajax({
            url: APP_URL   "/save_favorite",
            type: "POST",
            dataType: "json",
            data: {
                item: t,
                _token: $('meta[name="csrf-token"]').attr("content")
            },
            success: function(e) {
                1 == e.bool ? $("#save-icon-"   t).removeClass("text-muted").addClass("icon-filled") : 0 == e.bool && $("#save-icon-"   t).removeClass("icon-filled").addClass("text-muted")
            },
            error: function(e) {
                location.replace(APP_URL   "/targetPage?showModal=1")
            }
        })
    }

At the end of your target page add:

@if(isset($_GET['showModal'])  && $_GET['showModal'] == 1) 
<script type='text/javascript'>
    $(window).on('load', function() {
        $('#your modal id').modal('show');
    });
</script>
@endif

In your routes/web.php add this:

Route::get('/', function () {
    if(Auth::guest()){
        return view('target.page');
    } else {
        return redirect('/somewhere');
    }
});
  • Related