Jump to content

Javascript button that executes php-code?


arbitter

Recommended Posts

This is probably a very simple question, but I just can't figure it out. I've taken the javascript tutorials a while ago, now I went back to see what I needed but don't really find it.

 

So what I want to have is the following. A submit-type button with an ID, which is meant to delete a database with that same id. When the button gets clicked, the person first get's a popup with 'Do you really want to delete this table?' ad the buttons OK and cancel. It speaks to itself that when the person clicks cancel, nothing happens (or perhaps it get's shown 'Database was not deleted'), and when the person clicks OK, the PHP-code will reaload the same page with the $_POST['deletetable'] active.

 

For the button I found this code:

<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Do you really wish to delete this table?");
if (r==true)
  {
  alert("Database was succesfully deleted..");
  }
else
  {
  alert("Database was not deleted.");
  }
}
</script>
</head>
<body>

<input type="button" onclick="show_confirm()" value="Show a confirm box" />

</body>
</html>

 

 

But if I use this method, shouldn't there also be a form around the input button, and where and how should I set to execute the form?

 

I know this should be basic javascript stuff, but trying to get the hang of it...

Link to comment
Share on other sites

you're right this is easy...

 

your html button:

 

<input type="submit" name="button" id="button" value="do something" onClick="dothis(<?php echo $id; ?>);">

 

your javascript:

 

function AjaxObjectCreateGeneral()
{
var req;  // The variable that makes Ajax possible!

try{
	// Opera 8.0+, Firefox, Safari
	req = new XMLHttpRequest();
} catch (e){
	// Internet Explorer Browsers
	try{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e){
			// Something went wrong
			alert("Your browser broke!");
			return false;
		}
	}
}

return req;
}

function show_confirm(){
var r=confirm("Do you really wish to delete this table?");
    if (r==true)  { 
    req=AjaxObjectCreateGeneral();
if(req) {
	var myRand = parseInt(Math.random()*99999999);
	var url = "index.php?pg=blah&id="+id+"&int="+myRand

	req.onreadystatechange = function() {
if(req.readyState == 4) {
	if(req.status == 200) {
	//alert(req.responseText);
	}
}
};
	req.open("GET", url, true);
	req.send();
} 
    alert("Database was succesfully deleted..");  
    }else  {  
    alert("Database was not deleted.");  
    }
    }
    

 

that should get you started..  though look @ using prototypejs for your ajax (you still have to write your own functions) it's functionality is hard to surpass.

 

I modified my code to fit within your requirements of needing a confirm box prior to running the PHP code.

Link to comment
Share on other sites

it's not as difficult as it seems...

 

the first javascript function is left alone...

 

the showConfirm javascript function is where the changes will happen...

 

first change:

 

show_confirm(id){ (i missed that in my edit)

 

now to explain the code a little..

 

req=AjaxObjectCreateGeneral();

this is taking the ajax request into a variable is really all it is doing

if(req) { if the ajax connection is there do the following

 

var myRand = parseInt(Math.random()*99999999);  we create a random number to prevent browser caching

var url = "index.php?pg=blah&id="+id+"&int="+myRand - here we are setting up our request url (the PHP script) notice the id="+id, this is the id that is passed through to the function

req.onreadystatechange = function() { ajax.onreadystatechange -- not sure what it means (i dont use this method myself), but it seems to work (when i used to use it)

if(req.readyState == 4) { if readyState = 4 (forget what 4 means)

if(req.status == 200) { if status = 200 (200 is basically saying everything is ok and im done)

//alert(req.responseText); - with this you could do a multitude of things..  if you are outputing HTML you can do document.getElementByID(page).innerHTML = req.responseText; or you can even do window.location.href="eatit.html"; or whatever you wish to do really.

 

you can also further your checking like:

 

if(req.responseText == 0) {

alert('error! could not do something');

} else {

document.getElementByID('page').innerHTML = req.responseText;

}

 

}

}

};

req.open("GET", url, true); -- this is the open command, you can use GET, or POST, the url is the page we're opening, and the last means asynchronys or not asynchronys -- when i used this method i always used true.

req.send(); this sends the .open command and you can also use this when using a POST command like: req.send(formPars) or something of the like.

}

 

hope this makes you a little less confused, and a bit more knowledgable about what the code does.

Link to comment
Share on other sites

Probably a stupid question; but you said the html form would look like this:

echo"<input type='submit' name='button' id='button' value='verwijder' onClick='dothis(" . $id . ");'>";

 

But there is no function 'dothis()', should it be show_confirm($id)?

 

edit: Alright, I've got the buttons to work and display ok/cancel and the notifications that go with it!

Link to comment
Share on other sites

since you're combining your HTML, with your Javascript with your PHP, you'll want to create an entirely seperate PHP script to handle any and all ajax calls that you may have...

 

then you will change:

 

var url = "index.php?pg=blah&id="+id+"&int="+myRand

 

to point to the proper place to be run and remember to always add the &int="+myRand to prevent browser caching.

 

my recommendation for you is to create a php file called calls.php

 

then in there you would put:

 

<?php

 

$_pg = isset($_GET['pg']) ? $_GET['pg'] : '';

$_id = isset($_GET['id']) ? $_GET['id'] : '';

 

switch ($_pg) {

case delete_customers:

mysql_query("DELETE FROM whatever WHERE id = '".$_id."'");

echo html here;

break;

}

 

?>

 

doing this you can add multiple cases and achieve endless ajax calls from one file but doing very different things.... 

 

me personally, i keep all my JS in ajax.js, keep all css in style.css, keep all html in page_name.tpl, keep all php in index.php but i use a template engine that allows me to do that properly... 

Link to comment
Share on other sites

Pft this is all so difficult...

 

Is there no simple solution;

A php form with a sublmit button. Upon clicking this button, there's first a popup with OK and Cancel. If you click cancel the form is not submitted, if you click OK the form does get submitted...

Link to comment
Share on other sites

if you email me your entire code i'll get it setup for you and comment it for you so you can see what is being done and why ;D you can however edit out any database usernames / passwords as i wont need those to do what i would be doing.

Link to comment
Share on other sites

Pft this is all so difficult...

 

Is there no simple solution;

A php form with a sublmit button. Upon clicking this button, there's first a popup with OK and Cancel. If you click cancel the form is not submitted, if you click OK the form does get submitted...

 

Hmm...what you are doing sounds a lot like something that I got working a while back.  In my case I was specifically trying to get a table to reload without reloading the entire page, though reloading the entire page is certainly similar.  What you need to do to is use the confirm() function in Javascript and save its return value in a variable.  Then you can just test if the variable is true.  If so then submit the form.  You don't even need an else statement (which would just "do nothing" anyway).

 

I have the code skeleton posted here:

 

http://www.phpfreaks.com/forums/index.php/topic,287155.0.html

 

In that post I actually do use an else statement to "do nothing" but that is only because the GET request is made outside of the entire if/else structure (so that I didn't have to repeat code inside of both the add and the delete sections).

 

Are you sending a GET request or a POST request?  If it's GET then you can essentially just copy my code and move things around so that it looks like this:

 

<script type="text/javascript">
var xmlhttp;

function deleteUser(user)
{
  xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
    alert ("Sorry but your browser does not support AJAX or Javascript has been disabled");
    return;
  }

  var doAction = confirm("Are you sure you want to delete id #"+user+"?");
  if (doAction == true)
  {
    // we're deleting so append userID in the GET request
    var url = "deleteUser.php";
    url = url + "?delete=" + user;

    // execute the fully formed request
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
  }
}

function stateChanged()
{
  if (xmlhttp.readyState==4)
  {
    document.getElementById("myTable").innerHTML=xmlhttp.responseText;
  }
}


function GetXmlHttpObject()
{
  if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }
  if (window.ActiveXObject)
  {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
}
</script>

 

 

Then your backend script (in this case I have called it deleteUser.php) can simply check the value of $_POST['delete'].  If it's not empty then delete the user from the DB and redirect to the page that displays the table of users.

Link to comment
Share on other sites

Only thing you're missing really is the if xmlhttp.Status == 200, because after all,  we want only the output to be displayed when we return a status code of 200, everything else is a failure thus not something we want to display.

 

Though your code isn't anything different really than mine.  and your getXmlHttpObject function needs upgrated for better functionality across all browsers, and of course to catch the error in case something goes wrong with the browser itself.

 

but, all and all your code is virtually exactly like mine.  problem is, this guy is new to AJAX doesn't quite understand the grasp of it yet.  But once he can see some fully functional code that fits the needs he has, i am quite certain that he will have the light turn on.

 

So again if you email me the full code i'll get it all setup, i'll comment the hell out of it and email it back to you and then answer any questions you may have.  Although warning, i may stray from the code samples i have here, and get you working with the prototype.js framework for ajax calls.  I think it's easier and the functionality it has is hard to surpass.

 

i'll pm you my email address so you have it if you need it.

Link to comment
Share on other sites

Actually I was planning on doing it with $_POST...

 

Here's my whole script (with a little javascript from this thread in it)

<?php
session_start();
setlocale(LC_ALL, 'nl_NL');
require_once('mysql_connect.inc.php');
date_default_timezone_set('Europe/Brussels');
$verbinding = mysql_connect(MYSQL_SERVER, MYSQL_GEBRUIKERSNAAM, MYSQL_WACHTWOORD) or die("Verbinding mislukt: " . mysql_error());

//getting password & checking it
mysql_select_db('database');
$result = mysql_query("SELECT password FROM password");
$row = mysql_fetch_array($result);
$password = $row['password'];

if(isset($_POST['login']))
{
	if(sha1($_POST['password']) != $password)
	{
		$_SESSION['melding'] = 'U heeft een foutief paswoord ingegeven.';
		header('Location: riet.php');
		exit();
	}
	else
	{
		$_SESSION['aangemeld'] = true;
	}
}

//if you change the password
if(isset($_POST['changepas']))
{
$pas1 = sha1($_POST['pas1']);
$pas2 = sha1($_POST['pas2']);
if($pas1 != $pas2)
{
	$_SESSION['melding'] = '<div class=\'fout\'>De paswoorden komen niet overeen. Gelieve opnieuw te proberen.</div>';
	header('Location: riet.php');
	exit();
}
else
{
	mysql_select_db('database')or die(mysql_error());
	mysql_query("UPDATE password SET password = '$pas1'")or die(mysql_error());
	$_SESSION['melding'] = '<div class=\'juist\'>Uw paswoord is succesvol veranderd!</div>';
	header('Location: riet.php');
	exit();
}
}

//if not logged in; display login-form
if(!isset($_SESSION['aangemeld']))
{
	if(isset($_SESSION['melding']))
	{
		echo $_SESSION['melding'];
		unset($_SESSION['melding']);
	}
	echo "<form action='riet.php' method='post'><input type='password' length='20' name='password' /><br /><input type='submit' name='login' value='login' /></form>";
	exit();
}

//function to clean data
function CleanMyDirtyData($dirtydata)
{
	return mysql_real_escape_string(htmlentities($dirtydata, ENT_QUOTES,'UTF-8'));
}

//script that makes a new page
if(isset($_POST['maak']))
{
$content = nl2br(CleanMyDirtyData($_POST['inhoud']));
$omschrijving = nl2br(CleanMyDirtyData($_POST['omschrijving']));
if(empty($content) || empty($omschrijving))
{
	$_SESSION['melding'] = 'Je moet beide velden invullen!';
	$_SESSION['contenttextarea'] = $content;
	$_SESSION['omschrijvingtextarea'] = $omschrijving;
	header('Location: riet.php');
	exit();
}

function createPassword($length) 
{
	$chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$i = 0;
	$password = "";
	while ($i <= $length) 
	{
		$password .= $chars{mt_rand(0,strlen($chars))};
		$i++;
	}
	return $password;
}



mysql_select_db("database", $verbinding);
mysql_query("UPDATE voorbeeld SET devraag = '',omschrijving = '' WHERE id='1'");
$res = mysql_query("SHOW TABLES");
$row = mysql_fetch_assoc($res);
$tables = array();
while ($row = mysql_fetch_assoc($res))
{
	$tables[] = $row['Tables_in_database'];
}

while(in_array($naam, $tables)) 
{
	$naam = createPassword(;
}

$sql = "CREATE TABLE " . $naam . "(
	id int NOT NULL AUTO_INCREMENT, 
	PRIMARY KEY(id),
	devraag varchar(500),
	weergave varchar(500),
	naam varchar(500),
	inhoud varchar(500),
	tijd varchar(100))";

mysql_query($sql, $verbinding)or die(mysql_error());



mysql_query("INSERT INTO $naam (devraag, weergave) VALUES ('$content','kop')");
mysql_query("INSERT INTO databanken (naam, inhoud) VALUES ('$naam', '$omschrijving')");
echo "U hebt de nieuwe databank " . $naam . " gemaakt. U kunt deze <a href='http://test.fransdepypere.be/index.php?id=" . $naam . "'>hier</a> raadplegen.";

exit();
}


//The script that should be executed after 'OK' is clicked in the popup. (the page should just get reloaded). This deletes the page (DROP TABLE) and deletes it from a table 'databases', used to easily display all active databases.
if(isset($_POST['deletepage']))
{
$deleteid = CleanMyDirtyData($_POST['deleteid']);
mysql_select_db('database');
mysql_query("DROP TABLE $deleteid");
mysql_query("DELETE FROM databases WHERE name='$deleteid'");
//reload page without the $_POST variables anymore.
header('Location: riet.php');
exit();
}

//script that previews a new page
if(isset($_POST['bekijk']))
{
$content = nl2br(CleanMyDirtyData($_POST['inhoud']));
$omschrijving = nl2br(CleanMyDirtyData($_POST['omschrijving']));
if(empty($content) || empty($omschrijving))
{
	$_SESSION['melding'] = 'Je moet beide velden invullen!';
	$_SESSION['contenttextarea'] = $content;
	$_SESSION['omschrijvingtextarea'] = $omschrijving;
	header('Location: riet.php');
	exit();
}
mysql_select_db('database');
mysql_query("UPDATE voorbeeld SET devraag = '" . $content . "', omschrijving='" . $omschrijving . "' WHERE id = '1'");
header('Location: index.php?id=voorbeeld');
exit();
}

//if page-preview gets stopped
if(isset($_POST['terug']))
{
$omschrijvingtextarea = $_POST['omschrijving'];
$inhoudtextarea = $_POST['inhoud'];
unset($_POST['omschrijving']);
unset($_POST['inhoud']);
mysql_select_db('database');
mysql_query("UPDATE voorbeeld SET devraag = '',omschrijving = '' WHERE id='1'");
}
?>
<html>
<script type='text/javascript'>
function AjaxObjectCreateGeneral()
{
var req;  // The variable that makes Ajax possible!

try
{
	req = new XMLHttpRequest();
} 
catch (e)
{
	try
	{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch (e) 
	{
		try
		{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (e)
		{
			alert("Your browser broke!");
			return false;
		}
	}
}

return req;
}

function show_confirm(id)
{
var r=confirm("Wil je deze tabel echt verwijderen?");
    if (r==true)  
{ 
	req=AjaxObjectCreateGeneral();
	if(req) 
	{
		var myRand = parseInt(Math.random()*99999999);
		var url = "riet.php?id="+id+"&int="+myRand
		req.onreadystatechange = function() 
		{
			if(req.readyState == 4) 
			{
				if(req.status == 200) 
				{
				//alert(req.responseText);
				}
			}
		};
		req.open("GET", url, true);
		req.send();
	} 
	alert("The database was deleted succesfully.");  
    }
else  
{  
    alert("Database was not deleted.");  
    }
}
</script>
<?php

//if there's a notification it gets echoed
if(isset($_SESSION['melding']))
{
echo $_SESSION['melding'];
unset($_SESSION['melding']);
}

//give textareas the values it had when leaving page when one field wasn't filled in or when coming back from previewing it without making it
if(isset($_SESSION['omschrijvingtextarea']) && isset($_SESSION['contenttextarea']))
{
$omschrijvingtextarea = $_SESSION['omschrijvingtextarea'];
$inhoudtextarea = $_SESSION['contenttextarea'];
unset($_SESSION['omschrijvingtextarea']);
unset($_SESSION['contenttextarea']);
}

//some echoing
echo "Dit is de pagina waarop je je paginas kan beheren. Om slechts inhoud van databanken te beheren, dus om reacties te verwijderen bijvoorbeeld, moet je nog steeds naar de moderator pagina gaan van desbetreffende pagina.<br /><br />";
echo "<h2>Een nieuwe databank aanmaken:</h2><br/>";
echo "<form type='submit' action='riet.php' method='post'>Geef hier de omschrijving van de vraag <b>voor jezelf</b> in. Anderen zullen dit niet te zien krijgen.<br /><textarea rows='5' cols='50' name='omschrijving'>";if(isset($omschrijvingtextarea)){echo $omschrijvingtextarea;unset($omschrijvingtextarea);} echo "</textarea><br /><br />Geef hier de omschrijving van de vraag in <b>die iedereen te zien zal krijgen</b>:<br /><textarea cols='50' rows='10' name='inhoud'>" ; if(isset($inhoudtextarea)){echo $inhoudtextarea;unset($inhoudtextarea);} echo "</textarea><br /><input type='submit' value='maak aan' name='maak' /><input type='submit' value='bekijk' name='bekijk' /></form><br /><br />";
//echoing all existing databases
echo "<h2>Alle bestaande databanken:</h2><br />";
mysql_select_db('database');
$query  = "SELECT name, content FROM databases";
$result = mysql_query($query)or die(mysql_error());
echo "<table cellpadding='5' border='1'><tr align='center'><td><b>code databank</b></td><td><b>inhoud</b></td><td><b>gewone pagina</b></td><td><b>moderator pagina</b></td><td><b>verwijderen</b></td></tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
	//IN THE FOLLOWING LINE I WANT THE JAVASCRIPT/AJAX-BUTTON. the $row['name'] is the unique 8-letter code of the page.
	echo"<tr align='center'><td>" . $row['name'] . "</td><td>".$row['content']."</td><td><a href='http://test.fransdepypere.be/index.php?id=" . $row['naam'] . "'>bekijken</a></td><td><a href='http://test.fransdepypere.be/moderator.php?id=" . $row['naam'] . "'>beheren</a></td><td><form action='riet.php' method='post' type='submit'><input type='hidden' value='" . $row['name']. "' name='deleteid' /><input type='submit' name='deletepage' value='delete' onClick='show_confirm(" . $name . ");' /></form></td></tr>";
}
echo"</table><br /><br />";

//form to change password
echo "<h2>Het paswoord wijzigen.</h2><br /><font size=\'-1\'><i>(zowel voor riet.php als de moderator-paginas)</i></font><br /><form method='post' type='submit' action='riet.php'>Nieuwe wachtwoord:<input type='password' length='20' name='pas1' /><br />Verifiëer paswoord:<input type='password' name='pas2' length='20' /><br /><input type='submit' name='changepas' value='verander paswoord' /></form>";



?>

 

I ama aware that the html-tags and stuff isn't decent yet, I'm trying to get the php working first before I make a small interface for it. I am also aware of language-mixups. And if there is something else wrong it's solely from changing some dutch words to english so you could understand them.

 

Guys, already thanks for ll the attention you've given this issue. Was planning on stopping and doing it without the javascript/ajax popup, but trying to go through with it now though.

 

Link to comment
Share on other sites

Only thing you're missing really is the if xmlhttp.Status == 200, because after all,  we want only the output to be displayed when we return a status code of 200, everything else is a failure thus not something we want to display.

 

Though your code isn't anything different really than mine.  and your getXmlHttpObject function needs upgrated for better functionality across all browsers, and of course to catch the error in case something goes wrong with the browser itself.

 

Cool I didn't ever even think about checking if status==200 but that's a great idea!  I learned something new!

 

I was however, trying to make the code as simple as possible, just to illustrate the basic idea.

 

 

Actually I was planning on doing it with $_POST...

 

That's cool -- switching between GET and POST is really pretty simple.  I posted a thread on it a while back:

 

http://www.phpfreaks.com/forums/index.php/topic,288125.0.html

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.