I want to delete and page transition by pressing button.

Asked 2 years ago, Updated 2 years ago, 116 views

When button is clicked and name='action' is POSTed, DELETE is executed(); but
At this time, I would like to transition to home.php at the same time.

<button type='submit'name='action'value='delete'onclick="location.href='home.php'">
or
if($_POST['action']=='delete'){$stmt->execute();header("Location:./home.php"));}
I tried things like that, but it didn't work.

I tried to do a lot of research, but I could only do either transition or deletion at once.
If you know how to do it, please let me know.

$stmt=$db->prepare("DELETE FROM table WHERE url=:url");
$stmt->bindValue(":url", $url,PDO::PARAM_STR);
echo"<form method=\"post\"><button type='submit'name='action' 
value = 'delete'>Delete</button></form>";
if($_POST['action']=='delete'){
    $stmt->execute();
}

javascript php html database

2022-09-30 21:11

2 Answers

If the above code is action=delete's own processing, php will print a header if you echo inside.
In other words,

header("Location:./home.php");

does not move when you run .Also, I am concerned that a prepared statement for deletion has been made, but it is only done in if.

 if($_POST['action']=='delete'){
    $stmt=$db->prepare("DELETE FROM table WHERE url=:url");
    $stmt->bindValue(":url", $url,PDO::PARAM_STR);
    $stmt->execute();
    header("Location: ./home.php");
    return;
}

If you write like this, you will execute the delete query when action=delete, and then the screen transition will occur.


2022-09-30 21:11

How about controlling how JavaScript handles button pressing?

 document.querySelector("button [name='action']" ).onclick=function(){
  vardata={"name":"John Doe", "age":25}; // Data to POST
  var url = "./action.php"; // POST destination URL
  varxhr = new XMLHttpRequest();

  xhr.open("POST", url);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.timeout = 1000*30;
  xhr.onload=_onXHRLoad;
  xhr.onerror=_onXHRError;
  xhr.ontimeout=_onXHRTimeout;
  xhr.send(JSON.stringify(data)));

  /**
   * Handling of Successful Asynchronous Communication
   */
  function_onXHRLoad(ev){
    location.href="./home.php";
  };

  /**
   * Asynchronous Communication Error Handling
   */
  function_onXHRError(err){
    console.error("Error:", error);
    return false;
  };

  /**
   * Asynchronous Communication Timeout Processing
   */
  function_onXHRTimeout(err){
    console.error("Error:", error);
    return false;
  };
};


2022-09-30 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.