[英]How to flash message in Laravel after api post request with JavaScript?
Goal目标
Flash a message after a post request is saved successfully to database. Flash post请求成功保存到数据库后的消息。
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.如果反应前端收到成功消息,它会重新加载页面,如您在句柄提交handleSubmit
中看到的。 When a request is send from a form generated in the "standard laravel way", everythin works, like expected.当从以“标准 laravel 方式”生成的表单发送请求时,一切正常,如预期的那样。
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
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. React 前端中的相应函数片段。
handleSubmit
: 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:在saveData
function 中发送 post 请求:
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.我在没有重新加载页面的情况下解决了它,让 JavaScript 处理警报。 Thanks to elyas:)感谢 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.根据响应,我添加相应的警报。
You are using the javascript async functionality, and your page doesn't reload after send post data.您正在使用 javascript 异步功能,并且您的页面在发送发布数据后不会重新加载。 So you can put your message in json data and show it via javascript.因此,您可以将您的消息放入 json 数据中,并通过 javascript 显示。 in your Controller:在您的 Controller 中:
if ($report->save()) {
return response()->json(['success' => true, 'url' => '/admin/reports', 'success'=> 'Feedback gespeichert!'], 200);
}
And in JS file:在 JS 文件中:
if (response.success) {
alert(response.message);
window.location = response.url;
} else {
alert("Ein Fehler ist aufgetreten.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.