Making AJax Request in Laravel 5

Are you new to LARAVEL 5? If you tried moving your project from Laravel 4 to 5, you might have had an issue with handling form data with Jquery. This is because Laravel 5 uses CSRF (Cross-Site Request Forgeries) token validation for security reasons.

To make this work, I had my view, script, route and controller files of my L4 project edited as below:

In the View file:

<form id="test-parameters" method="get" action="http://localhost:8000/tests/setParams">
     <input type="hidden" name="_token" value="{{ csrf_token() }}">
     <div class="form-group">
       <label for="test-name" class="control-label">Test Name</label>
       <input type="text" class="form-control" id="test-name">
     <div class="form-group">
       <label for="test-description" class="control-label">Test Description</label>
       <textarea class="form-control" id="test-description"></textarea>

In the Routes file:

Route::get( '/tests/setParams', [
    'as' => 'testparameters',
    'uses' => 'TestController@setParams'

In the Controller file:

public function setParams(){
     //create new test
     $testname = Input::get('testname');
     $testdescription = Input::get('testdescription');
     return Response::json(
              'success'       => true, 
              testname        => $testname, 
              testdescription => $testdescription
          ], 200);

In the jQuery Script:

var defineTest = $.ajax({
     url: "/tests/setParams",
     type: "GET",
               '_token': CSRF_TOKEN,
     dataType: 'json'
     var testName = data['testname'];
     var testDescription = data['testdescription'];
     var stringResponse = "Creating Test: "+testName+"<br> Test Description: "+ testDescription;
     //Handle your Exception Here.I just decided to log mine in console.
     //Do not log in production
     console.log(“Error with defineTest function ”);

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *