Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tim3011's avatar

straight php to laravel syntax

I have a form that I would like a user to fill but during the filling of the form I want to populate some fields with data from the database .When a user clicks the select drop down and select something the select is suppose to trigger the ajax to call a control and populate part of the form.I have written this in straight php and it works now I want to translate it to laravel syntax here is my code so far tell me when you spot some thing wrong or out of the ordinary. code on the controller


public function getDriverNamePicture()
    { 
    
    if(isset($_POST['get_option']))
   { 

     $state = $_POST['get_option'];
     $sql = DB::table('driver')
            ->select('drvname')
            ->where('code', $state)
            ->first()
            ->drvname;
            $new_string = explode('', $sql);
   
     exit;
   }
   return Response::json( $sql);
    }

code on the route


Route::post('spotCheck', 'SpotCheckController@getDriverNamePicture');

code on the blade


//the script
<script type="text/javascript">

function fetch_select(val)
{
   $.ajax({
     type: 'post',
     url: 'spotCheck',
     data: {
       get_option:val
     },
     success: function (response) {
       document.getElementById("new_select").innerHTML=response; 
     }
   });
}

</script>

//the html

  {!! Form::Open(['url'=>'spotCheck','files' => true]) !!}
                {{ csrf_field() }}
                <div class="form-group">
                    <div class="row">
                       <div class="col-xs-8">
                          {!! Form::label ('Call Sign:',null, ['class'=>"control-label"])!!}
                          {!! Form::select('call_sign', $drive, null, ['class' => 'form-control' , 'id' => 'sel','onchange' => 'fetch_select(this.value);' ]) !!}
                       </div> 
                         <div class="col-md-4">
                           <label class="control-label">Picture</label>
                           <img src="Koala.jpg" alt="with responsive image feature" class="img-responsive img-circle">
                         </div>
                    </div>
                     <div class="row">
            <div class="col-xs-8">
                <label class="control-label">Start Time</label>
                <input type="text" class="form-control" name="stime" required />
            </div> 
        </div>
                </div>
                <div class="form-group">
                   <div class="row">
                     <div class="col-xs-8">
                       <label class="control-label">Driver First Name</label>
                       <input type="text" class="form-control" name="First_Name" id="new_select" />
                     </div> 
                  </div>
0 likes
12 replies
Snapey's avatar

watch your paths.

Your url is spotcheck so, if your current page is for instance /driver then the browser will try to fetch /driver/spotcheck

better to make the ajax url absolute rather than relative.

I don't believe you want that exit statement after the sql query.

tim3011's avatar

@Snapey The current page is spotcheck and I am not really familiar with ajax calls and ajax in generally if you would elaborate or show example or something I will be gratefull

Snapey's avatar

but you have not said that anything is actually wrong?

tim3011's avatar

@Snapey nothing happens it does not fire up or bring any error read something about a missing CSRF token not sure how to implement that

tim3011's avatar

@Snapey seen your reply somewhere about a similar question please advice been on browser network tools and this is what happens any help please.

Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:8000/spotCheck Failed to load resource: the server 
``
I guess my route is wrong please advice
DarkRoast's avatar

Under the Network tab you should see a list of resources that are loaded on the page.. when you make an ajax request that list should get updated and if you click on one of them it will open a pane where you can see a preview tab which should show you what the server is outputting rather than just the 500 status error.

Snapey's avatar

Can you show your routes.php file.

tim3011's avatar

@snapey

Route::post('spotCheck', 'SpotCheckController@getDriverNamePicture');
phpMick's avatar

Try this before your Ajax call:

   $.ajaxSetup({
            headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
            
        });

You need to pass the token with every AJAX call.

tim3011's avatar

@phpMick tried as per your suggestion nothing changes i will paste my code again if you can help please

on the blade i have this

<script type="text/javascript">
  $.ajaxSetup({
            headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
            
        });
function fetch_select(val)
{
 
   $.ajax({
     type: 'post',
     url: 'spotCheck',
     data: {
       '_token': '{!! csrf_token() !!}',
       get_option:val
     },
     success: function (response) {
       document.getElementById("new_select").innerHTML=response; 
     }
   });
}
</script>
<script type="text/javascript">
    
    function submit() {   
      form = document.getElementById('test_form');
      form.submit();      
    }
  
  </script>
  {!! Form::Open(['url'=>'spotCheck','files' => true,'id'=>'test_form']) !!}
                {{ csrf_field() }}
            
              <div class="form-group">
                    <div class="row">
                       <div class="col-xs-8">
                          {!! Form::label ('Call Sign:',null, ['class'=>"control-label"])!!}
                          {!! Form::select('call_sign', $drive, null, ['class' => 'form-control' , 'id' => 'sel','onchange' => 'fetch_select(this.value);' ]) !!}
                       </div> 
                         <div class="col-md-4">
                           <label class="control-label">Picture</label>
                           <img src="{{$dphoto}}" alt="with responsive image feature" class="img-responsive img-circle">
                         </div>
                    </div>
        </div>
        <div class="form-group">
                   <div class="row">
                     <div class="col-xs-8">
                       <label class="control-label">Driver Full Name</label>
                       <input type="text" class="form-control" name="First_Name" id="new_select"   />

on the controller

    public function getDriverNamePicture()
    { 
       if (Request::ajax()) 
    {
        if (Session::token() !== Request::header('csrftoken')) 
        {
            // Change this to return something your JavaScript can read...
            throw new Illuminate\Session\TokenMismatchException;
        }else if(isset($_POST['get_option']))
   { 

     $state = $_POST['get_option'];
     $sql = DB::table('driver')
            ->select('drvname')
            ->where('code', $state)
            ->first()
            ->drvname;
            $new_string = explode('', $sql);
   
     exit;
   }
    } 
    
   
   return Response::json( $sql);
    }
}

on the route I have this

Route::post('spotCheck', 'SpotCheckController@getDriverNamePicture');

I have gone on to add this to my layout file

 <meta name="_token" content="{!! csrf_token() !!}"/>

at the footer 
    <script type="text/javascript">
$.ajaxSetup({
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>

on the browser inspection I get this

send @jquery.min.js4
ajax @jquery.min.js4
fetch_select       @spotCheck:29
onchange @spotcheck:120

all that i understand what its saying but I get this at the end which i don't understand

Listpicker_handleMouseUp @about;blank:3138
Snapey's avatar

In your controller... Session token is not the same think as csrf token. They are separate things, and middleware should already be handling them for you.

Why does it need to be a post? You are getting a resource, not updating something on the server. Switch to a get request and remove the csrf complications?

Please or to participate in this conversation.