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
49.1k12 gold badges96 silver badges147 bronze badges
-
3Server-side logic cannot be executed on the client.Mr. Polywhirl– Mr. Polywhirl2016年04月12日 13:29:30 +00:00Commented Apr 12, 2016 at 13:29
-
1Some duplicates: stackoverflow.com/questions/3352576/… and stackoverflow.com/questions/8227638/…JCOC611– JCOC6112016年04月12日 13:30:48 +00:00Commented Apr 12, 2016 at 13:30
1 Answer 1
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.
answered Apr 12, 2016 at 13:29
georoot
3,6171 gold badge34 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
S.Adikaram
yeah as you say using ajax it would be easy. Thank you for the support.
Erhan Yaşar
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.
georoot
@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 ?
Erhan Yaşar
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.georoot
did you add type multicast to form ?
default