1

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. Commented Apr 28, 2020 at 17:26

1 Answer 1

1

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.");
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Thats, how i will do it :) So i can simply close the modal without reloading the page and show small message with JavaScript :)
Yes , that's wright. you can optionally use the sweet alert library. npmjs.com/package/sweetalert
I'm tryin to code most of the things by my self so that i will learn most :) But thanks for the hint, it works now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.