skip to Main Content

In my laravel project i have various checkboxes on my page.On checking of each checkbox i have to send coressponding Id’s to laravel controller.But its triggering an error.

Following is the code of ajax.

   $('.searchType').click(function() {
alert($(this).attr('id'));  
   if(this.checked){
        $.ajax({
            type: "POST",
            url: '{{ route('mapService') }}',
            data: $(this).attr('id'), 
            success: function(data) {
                alert('it worked');
                alert(data);
                $('#container').html(data);
            },
             error: function() {
                alert('it broke');
            },
            complete: function() {
                alert('it completed');
            }
        });

        }
  });

Following is the code of checkbox

<label class="control-label">Service</label> <br>
                @foreach($services as $service)
            <input type="checkbox" class="searchType" name="service[]" id="{!! $service->serviceID !!}" value="{!! $service->serviceID !!}">{!! $service->serviceName !!}<br>
                @endforeach

As per ajax code i have created a controller named mapService and following is the code

  public function mapService(Request $request)
    {
        $id = $request->input('id');

        echo $id;

    }

$id or corresponding is not getting in controller, It is generating following error

http://127.0.0.1/lifeloveandotherthings/public/api/mapService 405 (Method Not Allowed)

What is the problem here?Please help

2

Answers


  1. Add Csrf token and write ajax data like closing breket

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $('.searchType').click(function() {
            var id = $(this).attr('id');  
            $.ajax({
                type: "post",
                url: '{{ route('mapService') }}',
                data: {
                    id: id,
                },
    
                success: function(data) {
                  alert('it worked');
                  alert(data);
                  $('#container').html(data);
                },
    
                error: function() {
                 alert('it broke');
                },
    
                complete: function() {
                 alert('it completed');
                }, 
            });
        });
    
    Login or Signup to reply.
  2. Check is your route defined with POST and in your js part put something like this:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search