Laravel AJAX Request not working of a restful controller for a method

牧云@^-^@ 提交于 2019-12-13 04:42:51

问题


Laravel AJAX Request not working of a restful controller of a method.

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

The first link is worked as it is index method. And the second link is create method which does not work. Both code are same

http://thetoppinghouse.com/laravel/public/listing
http://thetoppinghouse.com/laravel/public/listing/create

Here you will get my code summary http://laravel.io/bin/roYBY

I have already post this question without live example here but could not get solution. Laravel Ajax request not working of a controller

Here is my AJAX code summary

// AJAX Requesst
 <script>
      $('#parent_ID').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>

And routes is here

// routes.php

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

回答1:


The problem is that your javascript code is making the ajax request to ajax-subcat?cat_id=1, a relative URL. This means:

/laravel/public/listing => /laravel/public/ajax-subcat
/laravel/public/listing/create => /laravel/public/listing/ajax-subcat

Since you already have your javascript inside the blade template you can easily let Laravel generate the URL:

 // AJAX
 $.get('{{ URL::to('ajax-subcat') }}?cat_id=' + cat_id, function(data){
     $('#subcategory').empty();


来源:https://stackoverflow.com/questions/27892051/laravel-ajax-request-not-working-of-a-restful-controller-for-a-method

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