Laravel Ajax request not working of a controller

我怕爱的太早我们不能终老 提交于 2019-12-06 15:03:07

问题


I am using laravel 4..2 and have a html onchange function like the image. And showing me the error as the second image.

This AJAX request does not work on create method but it works on index method of a laravel resource controller.

Its happening may be because of laravel controller. Can anybody help me by explaining this.

// Routes.php

Route::resource('index', 'IndexController');

    Route::get('ajax-subcat', function(){
        $cat_id = Input::get('cat_id');
        $subcategories = Subcategory::where('parent_ID', '=', $cat_id)->get();
        return Response::json($subcategories);
    });

// AJAX 

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

              var cat_id = e.target.value;

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

                           });

                      //  console.log(data);


                      });
              });

</script>

回答1:


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>


来源:https://stackoverflow.com/questions/27805325/laravel-ajax-request-not-working-of-a-controller

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