Ahmad Sharif
Ahmad Sharif

Reputation: 4435

Laravel Ajax request not working of a controller

enter image description here

enter image description here

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>

Upvotes: 0

Views: 1272

Answers (1)

Justin Kyle Parton
Justin Kyle Parton

Reputation: 120

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>

Upvotes: 2

Related Questions