AJAX Mail Sign-Up
By: Bryan Hunsinger
It's mandatory to keep up with new trends/technology, here is a litte taste the flavour of AJAX.
This easy tutorial to introduce you and others on AJAX. I'll show you how to create a simple sign-up form, when submitted.. will display a thank you message and will store the address on an existing mysql database.
- download sajax, once unzipped, copy the file Sajax.php, that you find in the folder PHP, on your webserver
- we start including sajax on our page
<?
require("Sajax.php");
- then we create a php function that will insert the mail in the db
function insertmail($x) {
$db = mysql_connect("localhost", "user", "pwd"); mysql_select_db("name_db",$db);
mysql_query("INSERT INTO table(field) VALUES('".$x."') ")or die(mysql_error());
return 0;
}
- now, we can inizialize sajax and declare the function just created
sajax_init();
sajax_export("insertmail");
sajax_handle_client_request();
?>
- ok, it's time to start to write our html code, obviously from the
head
<html>
<head>
<title>Ajax Mail Sig Up</title>
- then the script, including the code generated by the library
<?
sajax_show_javascript();
?>
- and now our scripts: the first javascript will take the mail just
inserted passing it to the php function and declare to execute the second
script
function js_insertmail() {
var x;
x = document.getElementById("m").value;
x_insertmail(x, js_thanks);
}
- the second javascript says thanks to our new user
function js_thanks() {
document.getElementById("mailsignup").innerHTML = "Thanks!";
}
- now, we close the script and head section and we write the html code
</script>
</head>
<body >
<div id="mailsignup">
<input type="text" name="mail" id="m" value="put your e-mail" size="20">
<input type="button" name="Sign-Up" value="signup" onclick="js_insertmail(); return false;">
</div>
</body>
</html>
- this is the entire code:
<?
require("Sajax.php");
function insertmail($x) {
$db = mysql_connect("localhost", "user", "pwd");
mysql_select_db("name_db",$db);
mysql_query("INSERT INTO table(field) VALUES('".$x."') ")or die(mysql_error());
return 0;
}
sajax_init();
sajax_export("insertmail");
sajax_handle_client_request();
?>
<html>
<head>
<title>Ajax Mail Sig Up</title>
<script>
<?
sajax_show_javascript();
?>
function js_insertmail() {
var x;
x = document.getElementById("m").value;
x_insertmail(x, js_thanks);
}
function js_thanks() {
document.getElementById("mailsignup").innerHTML = "Thanks!";
}
</script>
</head>
<body >
<div id="mailsignup">
<input type="text" name="mail" id="m" value="put your e-mail" size="20">
<input type="button" name="Sign-Up" value="signup" onclick="js_insertmail(); return false;">
</div>
</body>
</html>
save it with the extension .php, upload and enjoy !



