Missing params in Ajax Post request in Laravel

守給你的承諾、 提交于 2019-12-11 04:53:46

问题


I am trying to make an Ajax post request and pass params to use them in a query, but my params are always empty. Here is my code:

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

function searchPatient(){
    var params = {
        'name'      : $("#input-search-name").val(),
        'lastname'  : $("#input-search-lastname").val() 
    }
    console.log($('meta[name="csrf-token"]').attr('content'));
    $.ajax({
        data        :  params,
        url         : '{{ route("searchPatient") }}',
        contentType: "application/json",
        type        : 'post',
        beforeSend  : function(){
            console.log(params);
        },
        success     : function(data){
            //Inserto a la tabla principal el contenido
            $("#main-table-patients").html(data);
            //alert('exito');
        },
        error       : function(xhr, status, error) {
              var err = eval("(" + xhr.responseText + ")");
              console.error(err.Message);
        }
    });
}

And this is my web.php

Route::group(['middleware'=>'auth'], function(){
  Route::namespace('Patient')->group(function(){
    Route::resource('/patients','PatientController');
    Route::post('/patients/search/{name?}/{lastname?}','PatientController@search')->name('searchPatient');
  });
});

And this is my method in my controller

public function search($name = '', $lastname = '')
{
  $patients = '';
  $patients = Patient::where('name', 'like', '%'.$name.'%')
      ->Where('lastName','like','%'.$lastname.'%');

  return $name.' and '.$lastname;   
}

回答1:


It's an expected behaviour. You are sending in POST the variables but your route is designed to retrive the variables from the url. Decide what you want ... if you want to pass them in POST then your ajax call's url should be /patients/search and your route should be only

Route::post('/patients/search','PatientController@search');

your controller at that point can deal with $request object

public function search(Illuminate\Http\Request $request) {
    dd($request->all());
}

if you want to pass them in the url (not a good idea IMHO) then change your ajax call url to:

url: '/patients/search/' + params.name + "/" + params.lastname

This approach can cause problems in case one of the 2 params contains a "slash" (/)



来源:https://stackoverflow.com/questions/53088062/missing-params-in-ajax-post-request-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!