-3

I write php inside JavaScript in the following way. even though the delete function is working that alert doesn't come.

Here is my code:

Delete.php

<script type="text/javascript">
function delete_id(id) {
  if (confirm('Are you sure To Remove This Record ?')) {
    <?php
      include('database_connect.php');

      if (isset($_GET['variable'])) {
        $sql_query = "DELETE FROM register WHERE id=".$_GET['variable'];
        mysqli_query($con, $sql_query);
        header("Location: newusers.php");
      }

      mysqli_close($con);  
    ?>
  }
}
</script>
2

1 Answer 1

4

You can't do it like this. The correct way would be to make an ajax request to backend, and then have php delete the row.

Edit here is some sample code for you

<script>
function delete_id() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       alert("deleted");
    }
  };
  xhttp.open("GET", "/delete.php", true);
  xhttp.send();
}
</script>

and the delete.php goes like

<?php
//write code for delete here
?>

Another point is that header("Location...") would redirect but in ajax, hence it is better to not use php redirect, but check in javascript and then use document.location for the redirect.

Sign up to request clarification or add additional context in comments.

5 Comments

yeah as you say using ajax it would be easy. Thank you for the support.
I tried it as upload, but nothing happened or I couldn't make it work even simple php file does it. Do you guys have any idea on that? @georoot Tx.
@ErhanYaşar please add some details on what is the exact issue you are facing ? are you saying that you tried to upload some file and it didn't work ?
Well I changed the delete.php as upload.php the same here and used it inside window.onload function for file input addEventListener. It returns "File Uploaded" alert but nothing has uploaded to the server when I checked out.
did you add type multicast to form ?

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.