Khaled Rimawi
Khaled Rimawi

Reputation: 115

Internal server error 500 when using Ajax and Laravel

When I use Ajax for sending a post request I get an internal server error 500 and couldn't find a solution.

Here is my view that contains the Ajax:

<html>
   <head>
      <title>upload</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="/js/xhr2.js"></script>

      <script type="text/javascript">

         $(function(){

            $('#btn').click(function(){

              $.ajax({

                  url:"localhost:8000/test",
                  type:"POST",

                  dataType:'json',
                  success:function(data){
                  console.log(data);
              }
            });
           });
         });
      </script>
   </head>
   <body> 

    <input type="text" name="username" id="txt">
    <input type="button" name="btn" id="btn" value="send">


   </body>

</html>

and here is my controller:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class UploadsController extends Controller
{
    public function getUpload(){
        return view('upload');
    }

     public function postTest($request request){
         return response()->json(['name'=> 'khaled','age'=>45]);
    }
}

and my routes:

Route::get('/upload','UploadsController@getUpload');
Route::post('/test','UploadsController@postTest');

When I click the button, it should send and asynchronous post request, but an error "internal server error 500" returns instead.

Upvotes: 1

Views: 520

Answers (2)

diego
diego

Reputation: 428

the bug can occur because it is missing csrf-token

first, add the meta : <meta name="csrf-token" content="{{ csrf_token() }}">

Then, configure the headers of the ajax requests :

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

I hope it helped you

Upvotes: 1

Mahdi Younesi
Mahdi Younesi

Reputation: 7509

Wrong parameter definition for postTest fuction

public function postTest(Request $request){

     return response()->json(['name'=> 'khaled','age'=>45]);
}

Upvotes: 2

Related Questions