-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>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
S.Adikaram
  • 480
  • 5
  • 12
  • 3
    Server-side logic cannot be executed on the client. – Mr. Polywhirl Apr 12 '16 at 13:29
  • 1
    Some duplicates: http://stackoverflow.com/questions/3352576/how-to-embed-php-in-javascript and http://stackoverflow.com/questions/8227638/how-to-embed-php-script-in-javascript – JCOC611 Apr 12 '16 at 13:30

1 Answers1

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.

georoot
  • 3,557
  • 1
  • 30
  • 59
  • yeah as you say using ajax it would be easy. Thank you for the support. – S.Adikaram Apr 12 '16 at 14:20
  • 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. – Erhan Yaşar May 08 '17 at 08:49
  • @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 ? – georoot May 08 '17 at 09:50
  • Well I changed the `delete.php` as [upload.php](http://stackoverflow.com/questions/43122535/php-fileupload-with-pdf-docx-instead-of-image/43129226#43129226) 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. – Erhan Yaşar May 09 '17 at 07:09
  • did you add type multicast to form ? – georoot May 09 '17 at 07:32