简体   繁体   中英

Passing php-variable with JavaScript and HTML-Form

I am trying to create a Delete-button with a user confirmation-pop-up.

HTML/PHP:

<form method='POST' onclick='return confirmDelete()'>
  <button type='submit'>
    Delete script
  </button>
</form>

JavaScript:

<script type="text/javascript">
function confirmDelete() {
if (confirm("Are you sure?")) {
  window.location.href = 'delete_script.php?<?php echo "$id" ?>';
  return false;
}
else{
  return true;
  }
}
</script>

What it does is that it re-directs me to the correct page, "delete_script.php" but the $id does not appear in the url . The "delete_script.php"-page works with other pages, but I don't know what's wrong with this code. I really think it's possible. Any help would be appreciated!

As per my comment, change this...

if (confirm("Are you sure?")) {
  window.location.href = 'delete_script.php?<?php echo "$id" ?>';
  return false;
}

to this..

if (confirm("Are you sure?")) {
  window.location.href = 'delete_script.php?id=<?php echo $id ?>';
  return false;
}

You're expected to pass a url-encoded value for the query-string:

<?php echo 'id=' . urlencode($id); ?>

Alternatively, generate the whole url in php:

location.href = <?php echo json_encode('delete_script.php?id=' . urlencode($id)); ?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM