0
votes

I'mm using laravel 5.4 and I want to create AJAX that can post data to server but I got this error message

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

https://i.stack.imgur.com/gjIbU.png

Here's my AJAX

$('#testAjax').on('click',function(){
$.post('{{ route('edit') }}',{body:'string',_token:'{{ Session::token() }}'},function(data){
    console.log(JSON.stringify(data));
  });
});

My routes

Route::post('/edit',[ 'uses'=>'AjaxController@getProfessions', 'as'=>'edit']);

My Controller

public function getProfessions(Request $request)
{
  $this->validate($request, [
        'body' => 'required'
    ]);
    $p = profession::where('categories_id'=>$request['postId']);
    return response()->json(['new_body' => 'Server'], 200);
}

Currently I only want response 'Server' from the server instead of 'string' from ajax it self so i know it's coming from server

3
Hi Martin, what is the error messageWalter Cejas
@WalterCejas Failed to load resource: the server responded with a status of 500 (Internal Server Error)Martin Christopher
In the 90 percent of cases you can found the complete error, controller and line in your .log file in storage/logs, or also by clicking on the request in network, looking in the preview or response tab..Walter Cejas

3 Answers

0
votes

First, good practices in Laravel indicates that we should use the first letter of a model name in capital, perhaps that's your problem. Try to change it.

Profession::where...

Second, you don't handle the error response, you should add a function in your Javascript to handle it, like this:

error: function(data) {
    console.log(data)
}

Third, you're trying to get postId from the request, but you're not sending it.

Please change your code and let us know the result.

0
votes

You are using $.post incorrectly, try this:

$.post( "{!! route('edit') !!}", { body:'string',_token: {!! Session::token() !!} })
  .done(function( data ) {
    console.log(JSON.stringify(data));
  });
  • Check for the file and line of the error 500 in your log file (storage/logs).
  • Wrap your logic code into a try / catch to handle the error.
  • Use and IDE like PHPStorm with XDebug to debug the request, and check if every param of the request like the token and the string is correctly setted.
0
votes

in your routes/web.php

Route::post('/edit','AjaxController@getProfessions')->name('edit');

in your controller :

use Illuminate\Support\Facades\Validator;

public function getProfessions(Request $request)
{


 try {
        $validator = Validator::make($request->all(), [
                'postId' => 'required',
                'body' => 'required'
            ]
        );

        if ($validator->fails()) {
            $response=array('status'=>'error','errors'=>implode(',', $validator->errors()->all()));
            return response()->json($response, 200);
        }else{
           $profession = Profession::where(['categories_id'=>$request->input('postId')])->first();
           if($profession){
             $profession->body=$request->input('body');
             $profession->save();
             return response()->json(['profession'=>$profession], 200);
           }else{
               $response=array('status'=>'error','errors'=>'profession not found');
               return response()->json($response, 200);
            }

        }
   }catch(\Exception $e){
        $response=array('status'=>'error','errors'=>'Internal Server Error');
        return response()->json($response, 500);
  }
}

in your edit blade view , you are passing $profession to view then :

<meta name="csrf-token" content="{{ csrf_token() }}" />

<form>
    <input type="hidded" id="postID" name="postID" value="{{$profession->postID}}" />
    <input type="text" id="body" name="body" value="{{$profession->body}}" />
   <button type="button" id="testAjax">Submit using AJAX</button>
</form>

in your ajax function :

$('#testAjax').on('click',function(){
     var postID=$('#postID').val();
     var body=$('#body').val();
     $.ajax({
          url:"{{ route('edit')}}",
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
          type:"POST",
          dataType:"json",
          data:{
              postId:postID,
              body:body,
          },
          success:function(response){
              console.log(response);
          },
          error:function(err){

          }
     });
});