Use PHP to build your own Twitter-like system on your site
I was going to design my own how-to on this, but I had come across another great example on the IBM website, which shows you step-by-step how to create one.
Adding a microblogging or status update tool such as this doesn't require a whole lot of work, and it provides your users with a fun and simple way to communicate. The goal of this article is to show you how to do just that.
Twitter like textarea form and character count
To create this Twitter like textarea box and character count, we are going to use php and jquery. This is a three step process. You will need to download the jquery library. Once you have that, we are going to load the jquery library into our php script, and make sure that our DOCTYPE is in-place. You can call this file whatever you like - something like mytwitterbox.php.
First, open up the new php file you just created, and add an html header. Besure to include a DOCTYPE, and <HTML> tag as shown below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Textarea and Character Count
</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script> // the javscript file may look different for newer versions of jquery.
</head>
<body>
Second, within the body we will create a textarea form and character count. Notice the "maxlength" in the form, this is what the jquery ajax request will look for. So this must be in place.
<form method="POST" action=" mytwitterbox.php"> <div style="width: 400px;padding-top: 7px;"> <textarea style="width: 438px;height: 50px;" id="status" name="status" maxlength="140"></textarea> <p></p> <input type="submit" name="submit" value="Update" /> <span class="charsRemaining" style="padding-left: 10px;font-size: 20px;padding-top: 5px;color: #ccc;">140</span> </div> </form>
Third, we will create the jquery ajax request that checks for a textarea form, and it's "maxlength". If found then every time a character is added to that form, it checks against the number of characters to the "maxlength" of your form. It then subtracts, and displays the current count in the span above with the class name of "charsRemaining".
<script type="text/javascript">
$(document).ready(function(){
$('textarea[maxlength]').keyup(function(){
var max = parseInt($(this).attr('maxlength'));
if($(this).val().length > max){
$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
}
$(this).parent().find('.charsRemaining').html('' + (max - $(this).val().length) + '');
});
});
</script>
</body>
</html>
That's it. Hopefully this works for you. I did not take styling into play in this example so it may not look very pretty, but it'll work very well.
JQuery Contact Form with Facebox
This example will use basic css, and basic template files. Their will be three php files, one css file, and the jquery/facebox libraries. You can download a zipped file of this example here. If you would like to demo this example, click here.
First create a directory and name it whatever you like. Download the file above, and place those files into that directory. Below I will explain what these files do.
The index.php file is just a basic template file with a link to the contact form. It also includes some important header files. Notice the red items below. They must be in place for this to work. When you click on the Contact Us link, the facebox will appear, and the contact form page (contact.php) will load.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Jquery Contact Form with Facebox.</title>
<meta name="Keywords" CONTENT="jquery, contact form, billskinner.com, ">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8>
<meta name="robots" content="index,follow">
<link href="templates/default.css" rel="stylesheet" type="text/css" />
<link href="jquery/facebox/facebox.css" media="screen" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery/facebox/facebox.js"></script>
</head>
<body>
<div id="container">
<div id="mainBody">
<script type="text/javascript">
$(document).ready(function() {
$.facebox.settings.opacity = 0.5
$('a[rel*=facebox]').facebox()
});
</script>
<p style="margin-left: 10px;">This is a basic example on how to use a Jquery Contact Form with Facebox.</p>
<p style="margin-left: 10px;">By: <a href="http://www.billskinner.com">Bill Skinner</a></p>
<p style="margin-left: 10px;"><strong>Menu:</strong> <a href="index.php">Home</a> | <a href="contact.php" rel="facebox">Contact Us</a> | <a href="http://www.billskinner.com">Bill Skinner.com</a></p>
</div>
</div>
</body>
</html>
Second is the Contact Us page (contact.php). This is the page that will show up in your Facebox. This page will use an Ajax request to post the form values to the contact_submit.php page which will send out the email. If the request fails then an error message will pop-up on the screen. If the request is successful, then the form will be replaced with a success message.
<div id="title">Contact Us</div>
<div id="intro">Please feel free to contact us at anytime by filling out the following forms. All fields that are <strong>bolded</strong> are required.</div>
<script type="text/javascript">
$(document).ready(function(){
$("#submitform").submit(function(){
// 'this' refers to the current submitted form
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact_submit.php",
data: str,
success: function(msg){
$("#showerror").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
var result = '<p>Your request has been sent. You should receive a response from us by email or by phone within the next 12-24hrs.</p><p style="margin-bottom: 5px"> Looking forward to speaking with you.</p><p style="margin: 5px;"></p><p>Best Regards.</p>';
$("#form").hide();
$("#intro").hide();
}
else if (msg == 'FAIL1')
{
var result = '<p></p><div id=error>Please fill out all required fields.</div>';
}
else
{
var result = '<p></p><div id=error>There was a problem with your request. We apologize.</div><p></p>';
$("#form").hide();
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
<div id="showerror"></div>
<div id="form">
<p></p>
<form method="post" action="" id="submitform">
<div style="width: 500px;">
<div id="colWrap">
<div id="colLeft">
To:
</div>
<div id="colRight">
My Name
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Your Name:</strong>
</div>
<div id="colRight">
<input name="name" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Email Address:</strong>
</div>
<div id="colRight">
<input name="email" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
Phone Number:
</div>
<div id="colRight">
<input name="phone" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Subject:</strong></div>
<div id="colRight">
<input name="subject" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Your Message:</strong></div>
<div id="colRight">
<textarea name="message" cols="30" rows="5"></textarea>
</div>
</div>
<div style="padding-left: 0px;padding-top: 10px;clear: both;"><input type="submit" name="contactus" value="Send it"></div>
</div>
</form>
</div>
The third file is the contact_submit.php file. This file will be called from the contact.php ajax request. If successful your email will be sent, and your form will disappear and be replaced by a success message. You will need to change the name and email address highlighted in red to your own personal information. Also, for this to work, your server must be using PHP mail, which most do now anyway.
<?php
if(!empty($_POST)) {
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || empty($_POST['subject']))
{
echo 'FAIL1';
} else {
$mail_to= ucwords(strtolower("My Name"))."<myemailaddy@mydomainname.com>";
$mail_sub= $_POST["subject"];
$mail_mesg= "Name:\n".$_POSt['name']."\n\nEmail Address:\n".$_POST['email']."\n\nPhone Number:\n".$_POST["phone"]."\n\nMessage:\n".$_POST["message"];
$headers = "From: ".$_POST["name"]."<".$_POST["email"].">\r\n" .
"Reply-To: ".$_POST["name"]."<".$_POST["email"].">\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($mail_to, $mail_sub, $mail_mesg, $headers);
echo 'OK';
}
}
?>
Thats it. Hope this was easy to understand. Feel free to comment if you have any questions.
Contact Form Using PHP and JQUERY
So you want to create a contact form using PHP and the Jquery Framework. First you will need the jquery framework which you can download here. Jquery allows you to send a form to the server without having to reload the page. Otherwise known as AJAX. I did not include the .css for this example.
First we will move the file into the directory of your choice. In this example I am just going to put it into the root folder. After that you're going to have to create to two more files. In this example we will use ContactForm.php and ContactSubmit.php.
ContactForm.php
Contains your forms and jquery functions.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>My Jquery Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8>
<meta name="robots" content="index,follow">
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<div id="title">Contact Us</div>
<div id="intro">Please feel free to contact us at anytime by filling out the following forms. All fields that are <strong>bolded</strong> are required.</div>
<script type="text/javascript">
$(document).ready(function(){
$("#submitform").submit(function(){
// 'this' refers to the current submitted form
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "ContactSubmit.php",
data: str,
success: function(msg){
$("#showerror").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
var result = '<p>Your request has been sent. You should receive a response from us by email or by phone within the next 12-24hrs.</p>';
$("#form").hide();
$("#intro").hide();
}
else
{
var result = '<p></p><div id=error>Please fill out all required fields.</div>';
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
<div id="showerror"></div>
<div id="form">
<p></p>
<form method="post" action="" id="submitform">
<div style="width: 500px;">
<div id="colWrap">
<div id="colLeft">
To:
</div>
<div id="colRight">
My Business
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Your Name:</strong>
</div>
<div id="colRight">
<input name="name" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Email Address:</strong>
</div>
<div id="colRight">
<input name="email" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
Phone Number:
</div>
<div id="colRight">
<input name="phone" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Subject:</strong></div>
<div id="colRight">
<input name="subject" type="text" size="15">
</div>
</div>
<div id="colWrap">
<div id="colLeft">
<strong>Your Message:</strong></div>
<div id="colRight">
<textarea name="message" cols="30" rows="5"></textarea>
</div>
</div>
<div style="padding-left: 0px;padding-top: 10px;clear: both;"><input type="submit" name="contactus" value="Send it"></div>
</div>
</form>
</div>
</body>
<html>
ContactSubmit.php
PHP code used to trap errors or mail data from contact form.
<?php
if(!empty($_POST)) {
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || empty($_POST['subject']))
{
echo 'FAIL1';
} else {
$mail_to= ucwords(strtolower("Me"))."<myemailaddey@mydomainname>";
$mail_sub= $_POST["subject"];
$mail_mesg= "Name:\n".$_POSt['name']."\n\nEmail Address:\n".$_POST['email']."\n\nPhone Number:\n".$_POST["phone"]."\n\nMessage:\n".$_POST["message"];
$headers = "From: ".$_POST["name"]."<".$_POST["email"].">\r\n" .
"Reply-To: ".$_POST["name"]."<".$_POST["email"].">\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($mail_to, $mail_sub, $mail_mesg, $headers);
echo 'OK';
}
}
?>
I hope this gives you an idea on how Jquery and PHP can work together to perform a simple function such as submitting a contact form with very little effort.