I'm trying to make AJAX request with button in Laravel 5.5. Console returns me POST: 500 (Internal Server Error).
My Javascript code here:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#insertForm').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type: post,
url: url,
data: data,
dataType: 'json',
success:function(data)
{
console.log(data)
}
})
})
</script>
My HTML form code:
<form action="{{ URL::to('add') }}" class="translation-form" method="POST" id="insertForm">
<div class="language-area">
<textarea class="form-control wow fadeIn" data-wow-duration="0.5s" name="words" id="lang-input" rows="10"></textarea>
</div>
<p class="upload-info wow fadeInDown" data-wow-duration="0.5s" data-wow-delay="0.3s">
Add words from file
<input type="file" name="file-1" id="file-1" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple />
<label for="file-1"><span>"doc" or "docx"</span></label>
</p>
<div class="clearfix"></div>
<div class="text-center translate-option">
<button type="submit" class="btn btn-green btn-instant-translate wow fadeIn" data-wow-duration="0.5s">
Add
</button>
</div>
</form>
My AjaxController:
class AjaxController extends Controller
{
public function store(Request $request)
{
if($request->$ajax())
{
return "True request!";
}
}
}
And my route:
Route::post('/add', ['uses'=>'AjaxController@store', 'as'=>'ajaxAdd']);
Why does such an error occur? Ajax worked when I tried to just output the data in the console without usage requests to AjaxController.
the server responds with 500 because some exceptions are raised during the ajax call. i guess its because of the code in controller, the controller code should be like this
if($request->ajax())
{
return "True request!";
}
Edit: to respond to ajax request, you can use response objects and http response codes, instead of returning plain text, so that you can know the exact status of ajax call,