I have a task application, in which admin has the rights to edit task on the main page. Update is done on a new opened page,then show the results "Data saved",redirect to the main page and must convey the message "Edited" to the task on the redirected page. Maybe somebody can give me an advice about how to transfer a message to a redirected page from Ajax?
JS:
edit_form.addEventListener('submit', async(event)=>{
event.preventDefault();
try {
const response = await fetch(`/tasks/save/${id}`, {//обработчик action
method: 'POST',
body: new FormData(edit_form)
});
let answer = await response.text();
console.log("ответ сервера " + answer);
if (answer === true){
result.innerHTML = TASK_SAVED;
}else{
result.innerHTML = TASK_UNSAVED ;
setTimeout("window.location.replace('/')" , 2000);
}
}catch (error) {
console.log("ошибка", error);
}
});
PHP:
public function saveAction($id){
$saved_data=$this->request->post();
$saved =$this->mainservice->saveTask($saved_data, $id);
header('Content-Type: text/plain');
if ($saved ==="1"){
echo "Task saved";
}if ($saved ==="0")
echo "task isn't saved";
}
public function saveTask($saved_data, $id){
$sql = "UPDATE tasks SET name = :name, email = :email, textarea = :textarea , status= :status where id = :id";
$params =[
'name' => trim($saved_data['name']),
'email'=> trim( $saved_data['email']),
'textarea'=> trim($saved_data['textarea']),
'status' => trim($saved_data['status'][0]),
'id'=>$id
];
$dbConnection = $this->dbConnection->getConnection();
return $this->dbConnection->executeSql($sql, $params);
you can use session to tranfer message then catch by js function call it flash
save your edit result in $_SESSION['msg'] and $_SESSION['class'] to control msg color by bootstrap
in your php code
function flash() {
$message = $_SESSION['msg'];
$class = $_SESSION['class'];
if(!empty($message)){
echo '<div class="bg-'.$class.' msg-flash alert alert-warning alert-dismissible fade show" role="alert"
style="transition: all .9s ease; width:100%;" >'.$message.'<button type="button" class="close white "
data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>';
}
// empty $message after show
$message = "";
}
in your javascript code
function flash() {
// collect result from php session msg by http request
}
run function flash after every function in your javascript files and after dom loaded