Jumping to another page through a Confirm dialog, with variable values

Is it possible to pass along variables in a JS confirm dialog? Right now, the variables are passing literally instead of their variable values being passed. In this case, the $id variable is not being passed:

<input type='button' onclick='confirmation()' value='Delete'>

At bottom of page, right above the closing </body> tag:

function confirmation() {
	var answer = confirm("Delete the information? This action cannot be undone.")
	if (answer){
		window.location = "delete.php?id=' . $id . '";
		window.location = "stay-on-same-page.php";

If I do it this way, with no alert, then the variables are passed just fine:

<a href='delete.php?id=" . $id . "'> Delete</a>

I like to use the confirm dialog to make sure someone hasn’t clicked on the delete function accidentaly.

Assuming you have a button for each record, just pass the ID as an argument to your confirmation function like this:

<input type='button' onclick='confirmation(103)' value='Delete'>

and in your function, build the url like this:

function confirmation($id) {
    var answer = confirm("Delete the information? This action cannot be undone.")
    if (answer){
        window.location = "delete.php?id=" + $id;

1 Like

I assume

should be

If there is more than one variable, then I do
onclick=‘confirmation($id, $var1, $var2)’

Thanks a lot!

Are you talking about using variables that you set in your PHP code? If you’re passing values to JS functions, then you need to pass either the values themselves (i.e strings or numbers etc.) or variables that you’ve already assigned elsewhere in JS.

Assuming that you’re generating the links using PHP, then you’d be doing something like this:

<input type='button' onclick='confirmation(<?php echo $id ?>)' value='Delete'>

Yes, I was talking about PHP here. Sorry that wasn’t clear. Your last example makes more sense. I’m grateful!

Just remember that confirm() is for debugging only and should be removed before your script goes live. You don’t want your visitors disabling JavaScript for your page (the extra option that the confirm displays in some browsers) or disabling all fututre dialogs on your page (the extra option in most other browsers).

Thanks, Felgall; good point there!

This is for an Admin page at our company, so it should be fine.