Submitting a form via Fetch API in Laravel

540 Views Asked by At

I've been trying to submit the form via a Fetch API, but having no luck so far. I can submit the form without one, but for this exercise it has to be with Fetch.

Form

<form action="{{ url('/process')}}" method="POST">
       @csrf
       <div class="form-container">
         <div class="form-item">
           <label for="name">Full Name<span class="required">*</span></label>
           <input type="text" name="name" id="name" placeholder="Enter your name" />
         </div>   
         <div class="form-item">
            <label for="email">Email<span class="required">*</span></label>
            <input type="email" name="email" id="email" placeholder="Enter your email address" required />
         </div>
       </div>
       <div class="form-container">
          <button type="submit">Submit</button>
       </div>
</form>

^This submits successfully as is, but again I need to use Fetch. Fetch API:

form.addEventListener("submit", (e) => {
    e.preventDefault();
    const csrfToken = document.querySelector("input[name='_token']").value;
    fetch("success.blade.php", {
        method: "post",
        body: JSON.stringify(process),
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": csrfToken,
        },
    })
        .then((response) => {
            console.log(response);
            return response.text();
        })
        .then((text) => {
            return console.log(text);
        })
        .catch((error) => console.error(error));
}

Routes

Route::get('/', [ContactController::class, 'create']);
Route::get('/all', [ContactController::class, 'getAll']);
Route::post('/process', [ContactController::class, 'store']);

ContactController.php

public function store(Request $request)
    {
    $contact = Contact::create($request->input());

    $message = 'Thank you for your message! We will review your submission and respond to you in 24-48 hours.';

    if ($request->ajax()) {
       return response()->json(compact('message'));
    }
    return view('success');
}

success.blade.php is a file I created to display that thank you message, but something tells me I don't need it if I'm using this function store right.

If I remove action="{{ URL('/process') }} , and just use the Fetch API, then I get this error: The POST method is not supported for this route. Supported methods: GET, HEAD.

1

There are 1 best solutions below

0
Hossein Madhoushi On

you should not send fetch request to the blade you must send request to controller change url of fetch with controller