Example of Vanilla Javascript Fetch Post API in Laravel

javascript fetch api in laravel

I have been used to calling the AJAX request in my application via jQuery and haven’t got a chance yet to experiment with the latest fetch API of Laravel.

There can be a requirement in your application where you might need to make an AJAX call with Vanilla Javascript instead of using a library or a framework.
With the advancements in Javascript, it’s Fetch API makes it very easy to make an asynchronous HTTP request with Laravel.

For this example, consider you have an HTML button in your application, Clicking on which you want to make a POST AJAX call.

<button id="postFetchAPI">Click Me</button>

We attach the click event to this button via addEventListener method of javascript and attach a callback function to it.

document.querySelector('#postFetchAPI').addEventListener('click', onClick);

And here is the function onClick that gets invoked on clicking of the button.

  let url = '/laravel-fetch-example';
     let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

     function onClick(){
        fetch(url, {
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json, text-plain, */*",
                    "X-Requested-With": "XMLHttpRequest",
                    "X-CSRF-TOKEN": token
                    },
                method: 'post',
                credentials: "same-origin",
                body: JSON.stringify({
                    name: 'Tushar',
                    number: '78987'
                })
            })
            .then((data) => {
                window.location.href = redirect;
            })
            .catch(function(error) {
                console.log(error);
            });
     }

Notice that we have defined a variable named token just before the fetch call and also we are sending it as part of our request Header. To prevent Cross-site scripting, Laravel requires you to send a token on each of the POST requests. We can solve this by including a meta element on the page.

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

Now clicking on the button will invoke the Controller method tied to the POST URL, laravel-fetch-example if the POST URL in our example.

Now in the controller method, you can get the parameters in the request variable

    public function fetchExample(Request $request){
          $name = $request->get('name');
          $number = $request->get('number');
    } 

That’s all about making a POST Asynchronous request via javascript Fetch API in Laravel.

Related Articles

If you like our content, please consider buying me a coffee.

Thank you for your support!

Buy me a coffeeBuy me a coffee

Leave a reply:

Your email address will not be published.

Site Footer