简体   繁体   中英

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:

Route::get('/plots', 'PlotController@index'); 
Route::get('/plots/{testId}', 'PlotController@getData'); 

The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:

$(document).ready(function() {

  $('#sel_test').change(function() {
    var testId = $(this).val();
    console.log("testId=" + testId);

    $.ajax({
      url: 'plots/' + testId,
      type: 'get',
      dataType: 'json',
      success: function(response) {
        console.log("success");
      }
    });
  });
});

The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:

GET http://homestead.test/plots/1 500 (Internal Server Error)

I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?

EDIT: After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:

return $request->test_id;

It actually returns a more complex structure:

return view('plot')
    ->with('measurements',json_encode($result))
    ->with('events',json_encode($timeline))
    ->with('limits',json_encode($limits));

When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:

public function getData(Request $request) {
    Log::debug("made it to PlotController.php@getData");
    Log::debug("test_id="+$request->testId);

And here is the log output:

[2020-02-23 16:43:52] laravel.DEBUG: made it to PlotController.php@getData

The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:

testId=49 jquery.min.js:2 GET http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server Error)

Any ideas?

The easiest way is to get the data in Laravel Request . At least that's how I do it.

So your route shouldn't contain any parameter for that.

Your route will look like this:

Route::get('get-data-by-id', 'PlotController@getData')->name('get.data.by.id');

Your ajax should be like this:

$(document).on('change', '#sel_test',function(){
    var testId = $(this).val();
    $.ajax({
        type:'GET',
        url:"{{ route('get.data.by.id') }}",
        data:{'test_id':testId},
        success:function(data){
            console.log(data);
        }
    });
});

In your controller's getData() function just use Laravel Request to fetch the data.

public function getData(Request $request)
{
    // You can return the ID to see if the ajax is working
    return $request->test_id;
}

Make it post from Get for easier

At Web.php

Route::post('/list/plots', 'PlotController@getData')->name('getData'); 

At Blade file Ajax Request :

$(document).ready(function() {

 $('#sel_test').change(function() {
    var testId = $(this).val();
    var url = '{{ route("getData")}}';
    var token = "{{ csrf_token()}}";

   $.ajax({
     method:"post",
     url: url,
     data:{testId:testId,_token:token}
     dataType: 'json',
     success: function(response) {
       console.log("success",response);
     }
   });
 });

});

At Controller :

public function getData(Request $request){
  $testId = $request->testId;
  // Write your logic here
}

Try this. Hopefully work for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM