0
votes

I am trying to make an ajax call to a Laravel post method. But I get MethodNotAllowedHttpException. One of the possible issue can be mismatch of request type in ajax call and routes controller but that is not the case.

Using Postman, I can confirm that the Post route is working fine. That leaves me an option to focus on AJAX call.

Issue # 1

routes.php

Route::post('/test', 'HomePageController@test');

custom.js

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
 });

and then,

$('#teacher-save-submit').click(function(){
    
  var fname = $('#first_name').val();
  var lname = $('#last_name').val();
  var email = $('#email').val();
  var passkey = $('#passkey').val();
    
  $.ajax(function(){        
    type:"POST",
    url:"/test",
    dataType: "json",
    success:function(data){
      console.log("success");
      $('#sbt-result').html(data);
     }
   });
});

#Issue # 2

In console, it shows Uncaught SyntaxError: Unexpected token : at url:"/test"

It would be awesome If you people can share your experiences.

Thanks.

EDIT

This is what specific error I get. I think that is searching for some GET methods not Postserror_produced

2
Try posting the CSRF token in data in your ajax data: { '_token': token}, . Where token = '{{ csrf_token() }}'Andrew Nolan

2 Answers

0
votes

Maybe you have forgotten put the "meta" tag:

<meta name="csrf-token" content="{{ csrf_token() }}" />
0
votes

Change

Route::post('test', 'HomePageController@test');

js:

url:"{{url('test')}}",

and prevent the default click event

  $('#teacher-save-submit').click(function(e){
    e.preventDefault();
    //ajax call