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

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

enter image description here

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);
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x