Saturday, October 8, 2016

Laravel ajax and 500 internal server error

Hi Everyone

Today, we will learn what are the reason and their solution behind the 500 internal server error when using ajax in laravel. Sometimes when we use ajax with Laravel, it gives 500 internal server error. Following are the reasons:

CSRF:

The common reason behind 500 internal server error is missing CSRF token. In Laravel, CSRF token is required for all forms. People generally forget submitting the token with ajax request. Submitting token less ajax request results in 500 internal server error.

To fix this,  just add a hidden field in the form. Below is the code for us to add in our form:

1. For Blade Template Users:

 <input type="hidden" name="_token" value="{{ Session::token() }}">  

2. For non Blade Users:

 <input type="hidden" name="_token" value="<?php Session::token() ?>">  

3. Directly as ajax data:

 var request = $.ajax({  
  url: "test.php",  
  method: "POST",  
  data: { _token : <?php Session::token() ?>},  
  dataType: "html"  
 });  

This will solve your problem.

Other reason for this might be

WRONG ROUTE:

You may be submitting ajax data to wrong route type and even wrong url (404). So first double check the path you are submitting to. Second, check whether the route accepts “Post” or “Get” data type.
Because submitting post data via Get method or vice versa will results in Laravel ajax giving 500 Internal Server Error.

DATA TYPE RETURNED:

If you are returning Boolean and your ajax code is set for Json or any other data type then chances are that you will get internal server error. Try to set data type for all ajax response to json. If you are using jQuery then set dataType to xml.

 var request = $.ajax({  
  url: "/action",  
  method: "POST",  
  data: { id : userId },  
  dataType: "json"  
 });  

CROSS DOMAIN CONFIGURATION:

If you are using ajax for cross domain requests then be sure that you are sending proper headers.
In case of jQuery, just set the crossDomain variable to true. Alternatively set dataType to “jsonp”

.HTACCESS

Check your .htaccess file for any error specially after you have edited it.

Hope this will help someone.

Thanks


1 comment:

  1. Hi! Nice blog. We also offering youQuickbooks Phone Number . If you need any help regarding QuickBooks issues, dial 1-855-756-1077 for instant help.

    ReplyDelete