Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

takix's avatar
Level 1

Javascript Redirect Modal

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")
        }
    })
}
0 likes
2 replies
vincent15000's avatar

For me that's not a redirection, but only opening a modal component with the login form.

Instead of location.replace(...), I would write the necessary code to do something like loginForm.show().

underdash's avatar

If you want to perform a full HTTP redirect you can use below code.

window.location.replace("http://mysite.com/login");

If you want to open a modal on current page something like below snippet. (as @vincent15000 mentioned)

class LoginModal extends Modal {
 /*...*/
}
const loginModal = new LoginModal()
loginModal.show()

Last but not least, if modal is located in another page you can use "hash" event for triggering the modal and again perform a full redirect to the desired page.

window.location.replace("http://mysite.com/join#loginModal");

Please or to participate in this conversation.