andrian andrian - 19 days ago 5
PHP Question

Laravel Ajax response post method

My code below works when i use the get route.I just want to send data with ajax and then retrieve it back.

$('.link').click(function(){
var c = $(this).text();
var url = '{{route('home')}}';


$.ajax({

url:url,
data:{'mydata' : c }

})
.done(function(msg){
console.log(msg['response']);
});

});


and in my routes file :

Route::get('/home', function(Request $request){
return response()->json(['response' => $request['mydata']]);})->name('home');


It works fine when i am using get method in Route.When i am using post i get an error : 405 (Method Not Allowed).
I used method:'post' on AJAX and i get an error : 500 (Internal Server Error)

Anyone could help? thank you.

Answer

This will work:

$('.link').click(function(){
    var c = $(this).text();
    var url = '{{route('home')}}';


    $.ajax({
        type: "POST",
        url:url,
        headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
        data:{'mydata' : c  }

    })
    .done(function(msg){
        console.log(msg['response']);
    });

});

And in routes

Route::post(...