As the title suggests, this post explains how to implement an AJAX form using Laravel, React, and Superagent.
Superagent is chosen as the AJAX library because I wanted to move away from jQuery, and I found it easier to understand compared to jQuery's AJAX. While there is a complex concept called Promises, you can still use Superagent without fully understanding it for now.
From a web standards perspective, Fetch API seems to be the modern choice, but due to inconsistencies in browser implementations, I decided to avoid it.
Frontend development can feel chaotic at times, but let's move forward.
What We'll Do
- Set up an API in Laravel
- Convert FormRequest responses to JSON
- Use React to call Laravel's API with Superagent (verify GET and POST requests)
What We Won't Do
- Setting up the build environment
- Setting up React or Superagent
Laravel Implementation
The order is a bit random, so bear with me.
Routing
View
Skipping a lot here. This is just an example of how to summon the component.
Controller
In practice, I use a ResourceController to create a RESTful API, but I’ll skip the detailed implementation here.
Request (FormRequest)
To return errors as JSON with FormRequest, you just need to override the response method in Illuminate/Foundation/Http/FormRequest.
The usage is the same as the usual FormRequest. If there are errors, it will return the error messages as a JSON response.
CSRF Token Exception Settings
Don't forget to configure this in VerifyCsrfToken.php.
This completes the Laravel side.
React Implementation
Thoughts
I made this quite roughly, so there are likely many areas that need improvement.
While architecture is important, I realized I need to study modern JavaScript practices more to write code more flexibly.
References
- Things I looked into when creating an API with Laravel 5.1.x
- About the subtle but important
keyin React.js - This was important for iterating over responses from the API.