Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 + AJAX not working

Tags:

ajax

php

symfony

I am very new to Laravel 4 and I'm trying to test AJAX request.

In my script.js I have this:

(function() {
  $("#login-submit").click(function(e) {
    e.preventDefault();
    return $.ajax({
      type: "POST",
      url: "laravel/ajax/login", //i put my public in "localhost/laravel/public/"
      cache: false,
      data: 'email:' + $("#email").val(),
      success: function(data) {
        return alert(data);
      },
      error: function(response) {
        return alert("ERROR:" + response.responseText);
      }
    });
  });

}).call(this);

That is called from this html file:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>

<body>
    <form>
        <label for="email">Email: </label>
        <input type="text" id="email" />

        <label for="email">Password: </label>
        <input type="password" id="password" />

        <button id="login-submit">Log In</button>
    </form>

    <script type="text/javascript" src="assets/js/jquery/jquery.custom.js"></script>
    <script type="text/javascript" src="assets/js/script.js"></script>
</body>

</html>

Controller class:

class AuthController extends BaseController
{
    public function login()
    {
        echo 'success';
    }
}

And router:

Route::get('/', function() {
    return View::make('homepage');
});

Route::post('/ajax/login', 'AuthController@login');

By clicking Log In it should be echoing "success" but instead it throws this error:

ERROR:{
    "error": {
        "type": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
        "message": "",
        "file": "C:\\xampp\\htdocs\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php",
        "line":1429
    }
}

What's wrong in this?

like image 484
user2002495 Avatar asked Mar 23 '23 04:03

user2002495


1 Answers

Within the AJAX call, change:

  url: "laravel/ajax/login",

To:

  url: "ajax/login",

Your route is listening to ajax/login, not laravel/ajax/login.

Read more about routes here.

like image 169
Abdulaziz Avatar answered Apr 01 '23 22:04

Abdulaziz