Forum

Simple AJAX post response in LARAVEL 4

Hi there, I have the same problem I want to create a simple post in ajax but it seems I am having problem with the response. I always get a 500 Internal Server Error

I tried the solution of other thread : http://laravel.io/forum/01-31-2014-how-to-mark-up-forum-posts but it did not worked for me though so I am making my own thread.

This is my jquery script

<script>
        $("document").ready(function(){
            $("#frm").submit(function(e){
                e.preventDefault();
                var username = $("input#username").val();
                var token =  $("input[name=_token]").val();
                var dataString = 'username='+username+'&token='+token; 
                $.ajax({
                    type: "POST",
                    url : "admin/login",
                    data : dataString,
                    success : function(data){
                        console.log(data);
                    }
                },"json");

        });
        });//end of document ready function
    </script>

HTML FORM

<div id="loginfrm">
        {{Form::open(array("","id"=>"frm"))}}
        <!-- <form id="frm"></form> -->
        <label id="username-label">Username</label>
        <input type="text" name="username" id="username">
        <label id="password-label">Password</label>
        {{Form::password('password',array("class"=>"frmControl","id"=>"password"))}}
        {{Form::submit('Create User')}}
        </form>
    </div>

My Route Controller

Route::post('admin/login',array('before'=>'csrf','uses'=>function(){
    $data = Input::all();
    if(Request::ajax())
    {
        $u = new User;
        $u->username = $data['username'];
        $u->password = Hash::make(Input::get( $data['password']));
        //if success
        if($u->save()){
            return 1;
        }
        //if not success
        else{
            return 0;
        }

    }

}));

My Problem is every time I submit I always get an error: POST http://localhost/hotelcraze/admin/login 500 (Internal Server Error)

I am new to Laravel 4. Please help me with this issue Thank you in advance :-)

jersonandyworks
jersonandyworks
  • 3 years ago

you could narrow down the error guessing if you'd look into your log. if you're using artisan serve then you'll see immediately a stack trace upon an error or the same in a file under app/storage/logs/laravel.log.

also, your link to the previous used solution isn't right.

You have to use absolute url in javascript code something like.

var base_url = 'http://localhost'

$.ajax({
                    type: "POST",
                    url : base_url+"/admin/login",
                    data : dataString,
                    success : function(data){
                        console.log(data);
                    }

You are probably getting the error when sending the csrf token through to the post route.

If you try to use AJAX using these protected routes you hit a snag with Illuminates TokenMismatchException error.

There is a nice work around that you can do:

first, add the csrf token to your header:

<meta name="_token" content="{{ csrf_token() }}"/>

This should be added on any pages you plan to do ajax on, btw.

Next, we need to tell JQuery to pass this along every time a request is made through ajax. I put this into my submit() jquery method as the first process:

$.ajaxSetup({
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});

This essentially sets up a csrf token attribute in the request header without having to insert it through your ajax call.

Next step is altering the 'csrf' filter in your 'filters.php' file:

This will get you the logic needed for the filter to decide if the request from the route with csrf protection is using ajax:

Route::filter('csrf', function() {
    $token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
    if (Session::token() != $token)
        throw new Illuminate\Session\TokenMismatchException;
});

After all of this, it should work just fine. Oh, and darwingluague9001 is right about the url needing to be absolute.

Hope this helps.

ayyobro : Thanks for the solution. Worked perfectly for me !

This solution does not work for me. With xampp works without adding this solution. But now I'm testing with USBWebserver v8 and works not without or with this solution. Any idea?

Heyy same problem, 500 internal server error, Can u explain more where do i put the meta tag? In my controller? and can i put the jquery header in $.ajax { } of mine. I have the problem described here :

http://laravel.io/forum/08-30-2014-ajax-database-record-creation-not-working

Please help it, am fed up now! :p

A mi me funcionó!

Any updates ?

For the 500 Server internal error do not forget to add the token at the start:

<form method="POST" class="ajax" action="/login" accept-charset="UTF-8">
    <input type="hidden" name="_token" value="{{{ Session::getToken() }}}">

If you do not send the Session token it will raise a 500 error

This is my AJAX submit form for Laravel 4:

$('form.ajax button[type=submit]').click(function(e){
    e.preventDefault();

var form = jQuery(this).parents("form:first");
var dataString = form.serialize();

var formAction = form.attr('action');

$.ajax({
    type: "POST",
    url : formAction,
    data : dataString,
    success : function(data){
        alert("Testing ajax forms: " + data);
    }
    },"json");
});

Good luck!!

In Laravel 5 you can no loner use the Route::filter method mentioned by ayyobro. You have to add something like this to VerifyCsrfToken.php:

   /*
    * Determine if the session and input CSRF tokens match. 15      
    * * @param \Illuminate\Http\Request $request
    * @return bool 18 
    */
    protected function tokensMatch($request)
    {
    // If request is an ajax request, then check to see if token matches token provider in
    // the header. This way, we can use CSRF protection in ajax requests also.
        if ($token = $request->ajax())
        { 
          $request->header('X-CSRF-Token');
        } else {
          $request->input('_token');
        }

        return $request->session()->token() == $token;
    }

Route::filter is deprecated and REMOVED as of Laravel 5.2!!!

Great youtube video demonstrating the entire process.

https://www.youtube.com/watch?v=eoGITOPpBfU

They use a single line if/else but otherwise it's the same.

And lastly, here is the middleware page of the Laravel Manual (where VerifyCsrfToken.php is located):

https://laravel.com/docs/master/middleware

Unfortunately that video is no longer there :/

brianchristopherpeck said:

Great youtube video demonstrating the entire process.

https://www.youtube.com/watch?v=eoGITOPpBfU

They use a single line if/else but otherwise it's the same.