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 : but it did not worked for me though so I am making my own thread.

This is my jquery script

				var username = $("input#username").val();
				var token =  $("input[name=_token]").val();
				var dataString = 'username='+username+'&token='+token; 
					type: "POST",
					url : "admin/login",
					data : dataString,
					success : function(data){

		});//end of document ready function


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

My Route Controller

	$data = Input::all();
		$u = new User;
		$u->username = $data['username'];
		$u->password = Hash::make(Input::get( $data['password']));
		//if success
			return 1;
		//if not success
			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 :-)

zwacky replied 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.

darwinluague9001 replied 3 years ago

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

var base_url = 'http://localhost'

                    type: "POST",
                    url : base_url+"/admin/login",
                    data : dataString,
                    success : function(data){
ayyobro replied 3 years ago

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:

   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.

shwetasabne replied 2 years ago

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

MoZart182 replied 2 years ago

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?

Parthchokshi replied 2 years ago

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 :

Please help it, am fed up now! :p

zekinash replied 2 years ago

A mi me funcionó!

Mohamed Kawsara replied 2 years ago

Any updates ?

heroselohim replied 2 years ago

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){

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

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

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

Good luck!!

brianchristopherpeck replied 1 year ago

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())
    	} else {

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

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

brianchristopherpeck replied 1 year ago

Great youtube video demonstrating the entire process.

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

brianchristopherpeck replied 1 year ago

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

webdeva4 replied 6 months ago

Unfortunately that video is no longer there :/

brianchristopherpeck said:

Great youtube video demonstrating the entire process.

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

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us