Laravel Ajax request not working of a controller

谁说我不能喝 提交于 2019-12-04 20:43:14

Since your using Laravel, lets begin using laravel to its fullest:

In Routes.php, please create:

 Route::get('ajax-subcat/{id}', 'SOME_CONTROLLER_NAME@SOME_METHOD_NAME');

the "{id}" tells laravel to store the details of whatever comes after the "/" in a variable and pass it on to the specified controllers method. There is nothing more ugly than having ?ajax-subcat=cars in a URL. Also please replace SOME_METHOD_NAME and SOME_CONTROLLER_NAME with the correct names.

In your Controller, please add:

public function THAT_METHOD_NAME_FROM_THE_ROUTE($id){
  $subcategories = Subcategory::where('parent_ID', '=', $id)->get();
  return Response::json($subcategories);
}

And in your Ajax Script

   <script>
      $('#category').on('change', function(e){
          console.log(e);

          var cat_id = e.target.value;

          // AJAX
          $.get('ajax-subcat/' + cat_id, function(data){
                   $('#subcategory').empty();
                   $.each(data, function(index, subcatObj){
                  $('#subcategory').append('<option value="'+subcatObj.id+'">'+subcatObj.name+'</option>')

                       });

                  //  console.log(data);


                  });
          });

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