Xavier Issac
Xavier Issac

Reputation: 495

Ajax calling is not working on laravel project

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

Upvotes: 2

Views: 720

Answers (2)

knubbe
knubbe

Reputation: 1182

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

Upvotes: 0

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

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

Upvotes: 1

Related Questions