0
votes

Can you call a laravel route in javascript?

I am trying to implement a front-end validation with jquery validate plugin. The reason that I am doing a front-end validation instead of the validation function provided by laravel is that I am using a bootstrap modal for my login form and I do not want the user to dismiss the form upon clicking the "submit" button.

Currently I am doing something like this:

$("#modal-form-login").validate({
    errorClass: "error",
    errorPlacement: function(error, element) {
        error.insertAfter(element.parent("div"));
    },
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true,
            minlength: 4
        }
    },

    messages: {
        email: {
            required: "メールアドレスが必要です",
            email: "有効なメールアドレスを入力してください"
        },
        password: {
            required: "パスワードが必要です",
            minlength: jQuery.format("少なくとも {0} 文字")
        }
    },

    submitHandler: function(form) {
        $.ajax("http://mywebsite.com/login",{
            dataType: 'json',
            data: $('#modal-form-login').serialize(),
            success: function(response) {
                console.log("ok!");
            }
        });
    }
});

I understand that the post-validation handling should be in submithandler, and I want to call my doLogin route (which is reachable via {{ URL: to("doLogin") }} in blade), but can I achieve this in javascript?

2

2 Answers

1
votes

You don't want to be making php calls in your javascript. For that to work, your javascript file would have to be served by php. Your JS and CSS files should be static and should not be served by php. So the question you should be asking is "How do I inject values into javascript?" I like to pull urls out of the dom.

I'd set my login form to look something like this:

<form id="modal-form-login" method="post" action="{{ URL::to("doLogin") }}">

Then I'd update my submit handler to look like this:

 submitHandler: function(form) {
    $.ajax($('#modal-form-login').attr('action'), {
        dataType: 'json',
        data: $('#modal-form-login').serialize(),
        success: function(response) {
            console.log("ok!");
        }
    });
}

As you can see here, I'm pulling the url from the action of the form.

0
votes

There are a few packages that exist for using Laravel named routes in JS.

I personally maintain Ziggy and I've also heard good things about Laroute