1
votes

Goal

Flash a message after a post request is saved successfully to database.

Problem

The message doesn't appear when a post request comes from a react frontend. If the react frontend receives a success message it reload the page, as you can see in the handleSubmit function. When a request is send from a form generated in the "standard laravel way", everythin works, like expected.

So here is the code:

ReportsController:

use Illuminate\Support\Facades\Session;

...

public function store(Request $request)
  {
    $report = new Report([

      'name' => $request->get('name'),

      'body' => $request->get('body'),

      'visible' => $request->get('visible'),

      'show_in_slider' => $request->get('show_in_slider')

    ]);

    if ($report->save()) {
      Session::flash('success', 'Feedback gespeichert!');
      return response()->json(['success' => true, 'url' => '/admin/reports'], 200);
    }
  }

The line in the api.php

Route::resource("reports", "ReportsController");

The blade for the messages:

@if(count($errors) > 0)
@foreach($errors->all() as $error)
<div class="warning-modal">
  {{$error}}
</div>
@endforeach
@endif

@if(session("success"))
<div class="alert-modal">
  {{session("success")}}
</div>
@endif

@if(session("error"))
<div class="warning-modal">
  {{session("error")}}
</div>
@endif

The corresponding functions snippets in the React frontend.

handleSubmit:

async function handleSubmit(event) {
        event.preventDefault();
        const response = await saveData("/api/reports", report);
        if (response.success) {
            window.location = response.url;
        } else {
            alert("Ein Fehler ist aufgetreten.");
        }
    }

Sending the post request in the saveData function:

export default async function saveData(api, data) {
    const token = document
        .querySelector('meta[name="csrf-token"]')
        .getAttribute("content");
    const url = window.location.origin + api;
    const response = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": token
        },
        body: JSON.stringify(data)
    });

    const result = await response.json();
    return result;
}

So where is the fault?

Thanks for your time in advance :)

Edit

I solved it without reloading the page and let JavaScript handle the alert. Thanks to elyas :)

export default async function PostData() {
    const report = await CollectData();

    const response = await SaveData("/api/reports", report);

    const alert = document.createElement("div");
    alert.innerHTML = response.message;
    if (response.success) {
        alert.className = "alert-modal";
        ToggleNewReport();
    } else {
        alert.className = "warning-modal";
    }

    document.getElementById("content").appendChild(alert);
}

Depending on the response i add the corresponding alert.

1
Since that is an AJAX call, just pass that in JSON response and output it with JS if value is there. - Tpojka

1 Answers

0
votes

You are using the javascript async functionality, and your page doesn't reload after send post data. So you can put your message in json data and show it via javascript. in your Controller:

if ($report->save()) {
  return response()->json(['success' => true, 'url' => '/admin/reports', 'success'=> 'Feedback gespeichert!'], 200);
}

And in JS file:

if (response.success) {
        alert(response.message);
        window.location = response.url;
    } else {
        alert("Ein Fehler ist aufgetreten.");
    }