article

Wednesday, February 9, 2011

Simple AJAX with JQuery

Simple AJAX with JQuery





<script type="text/javascript">
function register(){ //when the button is pressed, this function will be executed.
$.ajax({
type: "POST", // AJAX function
url: "submit_data.php", //Method
data: "username=" + document.getElementById("username").value +
"&email=" + document.getElementById("email").value, // executed when the button is pressed.
success: function(html){
$("#response").html(html); //response html output echo
}
});

}
</script>

<form action="" method="post">
Simple AJAX with JQuery
<p>
<label for="name">Name:</label><br />
<input type="text" name="username" id="name" size="25" />
</p>
<p>
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" size="25" />
</p>
<p>
<input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/> //
</p>

</form>
<div id="response"></div> //The Response Div


submit_data.php
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_pass = 'pass';
$db_name = 'db';
$Username = $_POST['username'];
$Email = $_POST['email'];
// DB
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
$connection = $connect;
mysql_select_db( $db_name, $connect ) or die( mysql_error() );
// Inserting into DB
$qeuryInsert = mysql_query(" INSERT INTO `database` (`id`, `username`, `email`)
VALUES ( ``, `$Username`, `$Email`)
");
if ($qeuryInsert){
echo "You are now subscribed to our newsletter. Thank you!";
} else {
echo "Error!";
}

?>

Related Post