Thursday, September 21, 2017

jQuery ajax post not working in Laravel 5.3

Here's the issue jQuery ajax post not working in Laravel 5.3 (could be occurring to other version too).

So here's the details, I created a jQuery ajax post to our Laravel backend. You might ask, why not just VueJS or other JS framework? Well, basically just a simple ajax request so why bother.

For a developer like me who immediately get his feet wet without reading in development, I would keep on trying until it'll work.

My jQuery code goes below:

      var request = $.post("/api/requestkoto",{
                data: {
                    'fieldOne': fieldOne,
                    'fieldTwo': fieldTwo,
                }
            });

For web developers, browser's developer console is their friend. It was pain in the ass to see that your request is not working. From the console the POST is turning to GET. I started to wonder and feeling lost. Where and Why it's happening?

 Tried using jQuery or $.

I also I tried disabling Larave's security by commenting out \App\Http\Middleware\VerifyCsrfToken::class, at HTTP/Kernel wherein my post started to work. Of course, it wasn't the solution.

Well, it turns out it's Laravel's security feature which states and can be found here.

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">
And you have to add this your code too.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
So with that, I my new ajax POST request would be

      var request = $.post("/api/requestkoto",{
                data: {
                     '_token': window.Laravel.csrfToken, 'fieldOne': fieldOne,
                    'fieldTwo': fieldTwo,
                }
            });
I just added  '_token': window.Laravel.csrfToken to the request and everything works as expected. Spent more than 1 hour tracing from backend to javascript.

Okay. That's it for now.

Welcome to PH Devlog

Hi!

I'm a Web Developer from Philippines and I just created this blog to serve as my logs on web development.

This could be a log of simple or even complex issues that I encountered during the development process. Creation of this blog has been in my mind for quite a long time now but today I decided to start it.

So that's it for now.

Ciao!

- ian v