skip to Main Content

I’m sending a POST request to my ItemController, the request came through and the response can be generated. But I am unable to extract the data passed by the AJAX request.

Here’s a snippet script/blade template content: layout.blade.php:

<script>
$("#ajaxRequest").click(
    function(){
        $.ajax({
            url: '/itemAjaxReq',
            type: 'POST',
            dataType: 'html',
            contentType:'application/json',
            headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            data: 
            { 
                data1: 'ABC', 
                data2: 'DEF'                       
            },
            error: function() {alert('Error');},
            success: function(response) {                                                    
                        $('#ajaxResponse').empty();
                        $('#ajaxResponse').append(response);
                    }
    });
</script>

<div>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <button id="ajaxRequest">Test ajax request</button>
</div>

<div id="ajaxResponse">
</div>

Route: web.php

Route::post('itemAjaxReq','ItemController@ajaxReq')->name('items.ajaxReq');

Model: ItemController.php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppItem;
use IlluminateValidationRule;

class ItemController extends Controller
{   
    //... some skipped functions
    public function ajaxReq()
    {
        if(request()->ajax())
        {
            error_log("This is an AJAX Request");
            //dd(request());
            $data = request()->all();
            //dd($data);
            error_log("Request :n" . request() . "n");
            error_log("data1 : " . request()->input('data1'));
            error_log("data2 : " . request()->data2);
            error_log("data3 : " . request()->data3);
            return "Response :n"."Some data here";
        }
    }
}

If I uncomment the dd($data), I got empty array ([]). If I uncomment the dd(request()), then the data appear on the protected variable #content. Here’s the snippet:

IlluminateHttpRequest {#51 ▼
  #json: SymfonyComponentHttpFoundationParameterBag {#43 ▶}
  #convertedFiles: null
  #userResolver: Closure($guard = null) {#31 ▶}
  #routeResolver: Closure() {#253 ▶}
  +attributes: SymfonyComponentHttpFoundationParameterBag {#53 ▶}
  +request: SymfonyComponentHttpFoundationParameterBag {#43 ▶}
  +query: SymfonyComponentHttpFoundationParameterBag {#59 ▶}
  +server: SymfonyComponentHttpFoundationServerBag {#55 ▶}
  +files: SymfonyComponentHttpFoundationFileBag {#56 ▶}
  +cookies: SymfonyComponentHttpFoundationParameterBag {#54 ▶}
  +headers: SymfonyComponentHttpFoundationHeaderBag {#57 ▶}
  #content: "data1=ABC&data2=DEF"
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/itemAjaxReq"
  #requestUri: "/itemAjaxReq"
  #baseUrl: ""
  #basePath: null
  #method: "POST"
  #format: null
  #session: IlluminateSessionStore {#273 ▶}
  #locale: null
  #defaultLocale: "en"
  -preferredFormat: null
  -isHostValid: true
  -isForwardedValid: true
  basePath: ""
  format: "html"
}

If I expanded +attributes, +request, and +query properties, I got #parameters: []

Did I make mistake when passing the data? How do I extract it from the content attribute?

2

Answers


  1. Chosen as BEST ANSWER

    OK, I've solved the issue. But I don't understand why the solution works.

    I changed the AJAX request contentType from contentType:'application/json' to contentType:'application/x-www-form-urlencoded'

    The problem isn't on using not using $request, nor fetching it via ->post('data1') or ->input('data1'). Using request() or directly fetching it by ->data1 works fine.


  2. For Laravel >= 5.5, you can simply call

    $request->post() or $request->post('my_param')
    

    which internally calls

    $request->request->all() or $request->request->get('my_param')
    

    respectively.

    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search