Max
Max

Reputation: 163

Ajax request yields 404 in Laravel

I am trying to update a SQL table after a user clicks on a button. I am using Laravel, and having trouble making the ajax call work, i.e. i get a 404 response. My current approach was to route the request to a Route that would pass it to the controller. Could anyone please help me understand my mistake(s)?

ROUTE

Route::post('/controllers/AccountController', array(
'as'    =>  'userManagementAjax',
'uses'  =>  'AccountController@deleteAccount'
));

CONTROLLER

public function deleteAccount(){
        if($_POST['action'] == "delete") {
        DB::table('users')
            ->where('email', $_POST['email'])
            ->update(array('suspended' => 1));
        echo "ok";
        }
    }

HTML & JAVASCRIPT

   <script>
    function rmuser(a) {
    alert('Removing user: '+a);                
    $.ajax({
      url: '/controller/userManagementAjax',
      type: 'POST',
      data: {'action': 'delete', 'email': a},
      success: function(data, status) {
        if(data == "ok") {
          $('#tr'+a).remove();
        }
      },

      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call
};

</script>

    <button class="btn" onclick="rmuser('some_email')">Delete</button>                   

Upvotes: 1

Views: 1432

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

Your route defines this URL:

/controllers/AccountController

And your AJAX is submitting to this URL:

/controller/userManagementAjax

So you should be getting a 404 error on your ajax call.

The as syntax in your route simply denotes a named route. The first argument to the Route::post call should be the URI you're expecting, not the controller name (the controller name should be used in the uses key in the second array parameter).

I think this is what you're going for with your route:

Route::post('/controllers/userManagementAjax', array(
    'as'    =>  'user.delete',
    'uses'  =>  'AccountController@deleteAccount'
));

The first string parameter must match the URL you are attempting to post to with AJAX.

To take advantage of the named route, you can now redirect to user.delete or generate a link to the route user.delete like this:

// Redirect to named route from controller
return Redirect::route('user.delete');

// Display link in blade template to named route
<a href="{{ URL::route('user.delete') }}">Delete User</a>

The benefit of using named routes is basically that you can change the URL's in your routes.php file at will as long as everything else that relies on them is referencing the name rather than the URL.

Upvotes: 1

Related Questions