0

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

1
  • Try posting the CSRF token in data in your ajax data: { '_token': token}, . Where token = '{{ csrf_token() }}' Commented Jul 21, 2016 at 4:38

2 Answers 2

0

Maybe you have forgotten put the "meta" tag:

<meta name="csrf-token" content="{{ csrf_token() }}" />
Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

I generally use {{action('Controller@method')}}, however, it still worked in my project when I specified the URL as he did for my particular request.
@madalin, I've edited the post. Check the screenshot. I think it's sending a get request.
@NaumanZafar you aren't doing a ajax call at all you are doing a page redirect see my updated answer
@AndrewNolan . I also checked that but doesn't work for me. Can you please see the screenshot. I think laravel is looking for a Get Request
@Nauman Zafar, it was more in relation to this answer. I wasn't sure if your url would work.I have a few ajax request in my project and I tried it out how you declared the url and it works just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.