Cevil
Cevil

Reputation: 215

Routing in laravel, resolving URL in ajax

So I'm trying to understand routing in laravel, without much success I'm afraid. My current issue is that I am trying to route so that my login function, which is checked using ajax, is accessible from all pages on the site. At the moment i can only reach it from my index. i use the following

Route::post('login', array('uses' => 'LoginController@doLogin'));

and the following ajax:

    $.ajax({
        type: "POST",
        url: "<%= ResolveUrl("~/login") %>",
        data: "username="+username+"&password="+password,
        success: function(data) {
            console.log(data)
            if(data == 'Fel användarnamn eller lösenord.') {
                document.getElementById('loginerror').innerHTML = data
            } else if (data == 'Inloggad'){
                document.getElementById('loginerror').innerHTML = data;
                window.location.reload(true);
            }

Now it is to my understanding that resolving the URL would possibly solve my issue. However, no matter i manipulate the url part, I cant get the resolve to work. I only get syntaxerrors or bad request errors. If there's something built in into laravel for this, to get the correct route independently of changes in the URL, I would greatly appreciate any tip of such functionality. I cant find/understand anything in the documentation that would solve my problem. Else if anyone could tell me how to write the ResoleUrl correctly, that would also be greatly appreciated. however an understanding of laravels routing would probably serve me better! Thanks beforehand!

Upvotes: 0

Views: 4797

Answers (3)

user1669496
user1669496

Reputation: 33048

Let Laravel do it for you.

Name your route...

Route::post('login', array('uses' => 'LoginController@doLogin', 'as' => 'ajax.doLogin'));

Link to your route by the name in Javascript...

url: "{{ URL::route('ajax.doLogin') }}",

Upvotes: 0

Lee
Lee

Reputation: 20914

Try this in your route.

Route::any('login', ['uses' => 'LoginController@doLogin', 'as' => 'login']);

Upvotes: 0

Lee
Lee

Reputation: 10603

Change the url in your ajax to:

url:"/login"

Upvotes: 4

Related Questions