This tutorial cover some of basics about jQuery and AJAX. We will build AJAX form submit where we will have 1 field. If we lave it blank and submit our form, we will get error message. If we fill it with some data we will get that text. We will also add some loader image. So first we have to create some folder structure.
After that we can start creating our files. You can download jQuery here. First we have index.php. That is our main file and it will have form. Our AJAX calls are made from that file to post.php. Here is index.php source code.
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Antispam form</title>
<link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
</head>
<body>
<div id="wrapper">
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form action="" id="demoForm" method="post">
<fieldset>
<legend>Demo form</legend>
<span style="font-size: 0.9em;">This ajax submit demo form.</span>
<p>
<label for="email">E-Mail:</label>
<input type="text" name="email" id="email" value="" />
</p>
<p>
<input type="submit" name="submit" id="submit" style="float: right; clear: both; margin-right: 3px;" value="Submit" />
</p>
</fieldset>
</form>
</div>
<script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
</body>
</html>
This is our main.css file.
@CHARSET "UTF-8";
body {
background-color: #f0f0f0;
}
#wrapper {
margin: 100px auto;
width: 310px;
}
#email {
width: 248px;
}
#text {
width: 248px;
height: 70px;
}
#waiting {
color: #767676;
text-align: center;
}
fieldset {
margin-top: 10px;
background: #fff;
border: 1px solid #c8c8c8;
background-color: #fff;
}
legend {
background-color: #fff;
border-top: 1px solid #c8c8c8;
border-right: 1px solid #c8c8c8;
border-left: 1px solid #c8c8c8;
font-size: 1.2em;
padding: 0px 7px;
}
label {
display: inline-block;
width: 50px;
}
.success {
width: 298px;
background: #a5e283;
border: #337f09 1px solid;
padding: 5px;
}
.error {
width: 298px;
background: #ea7e7e;
border: #a71010 1px solid;
padding: 5px;
}
Now we need to create our javascript file that will do request. We are building ajaxSubmit.js file.
First we ensure that our document is loaded. After that we add event listener to our element with id #submit (that is our submit button). When we click on that button anonymous function is executed. That function makes AJAX call. When we start our AJAX call first we show our loader (id is #waiting), then we hide our form (id is #demoForm) and message if there was any (id is #message). We initialize our AJAX call and create some setting. We set our type to POST, url to post.php and dataType (data type that is returned from server) to json. Then we set our data to be sent. We provide our data as an object. Our object looks like “{name : ‘value’, name1: ‘value1′, …}” . That object is translated into request string and sent to server as “name=value&name1=value1&…”. Next we just add two more anonymous functions. They are called when our AJAX is executed successfully or when we have error. Function that is called when we have success takes 1 argument and that is data returned from server (in our case in JSON format). We hide our loader, remove any class that was there before and then add new. In our response we get and object with 2 variables (msg and error). If error is true we add class error, otherwise we add class success. After that we add our message from response to that element and show it. If our response was an error we show our form as well. Last we have error function that is called when request was not received or our AJAX call fails. It accepts 3 arguments (but they are not important to us now). In that function we hide our loader, remove class from message element, add error class, add text with message “There was an error.” and show our message. We also show our form. On the end our listener function returns false. If we would not return false our form would be submitted as regular post, but since we return false it is not submited. You can read more about jQuery AJAX here. This is how our ajaxSubmit.js file looks.
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
Now we just need to create our file that handles requests from our AJAX call. That file is post.php (we told so to our AJAX). At the beginning we add sleep(3);. We add that just so we could see our loader show and test that it works ok. That function delays PHP script execution for x seconds (in our case 3). Since we do it ll locally our requests are processed almost instantly (about 20ms are required to process request and get response). After that we check if user has entered his e-mail address. If he did not we create new array (that array will be converted to JSON object) with keys error and msg. We set error to true and msg to “You did not enter you email.”. If he did entered his e-mail address we set error to false and msg to “You’ve entered:” plus e-mail that he entered. At the end we convert our array to JSON object and echo it. That is response recieved by our AJAX call.
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
Here are some screenshots of our form in action.
You can download source code from here or view demo here.
Thanks for reading.
Update: As Pre requested, I’ve created extended version. You can view it here or download here.
I think problem could be in this.each because this is not jQuery object, but Javascript object. Try return $(this).each… insted (I may be wrong but you should try
.
yap… because it displays the loading image.
Are you sure your function gets called?
I did use firebug. It doesn’t display anything it doesn’t steps to neither succes or error function.
What doesn’t work? You get no response or there is jQuery problem? Use Firefox with Firebug, that will make your life a lot easier
.
i have the following script, built following the example you posted:
(function ($) {
$.fn.rss=function(opts)
{
var opts=$.extend({url:’public/rss/rss.xml’}, opts || {});
return this.each(function()
{
$(‘#rssLocation1′).empty();
$(‘#rssLocation1′).append(”);
$.ajax({
cache:false,
type:”GET”,
url: ‘xmlhttp.php?url=’+escape(opts.url),
dataType: “html”,
succes: function(data)
{
$(‘#rssLocation1′).empty();
$(‘#rssLocation1′).append(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{ $(‘#rssLocation1′).empty();
$(‘#rssLocation1′).append(‘News failed to load, error!‘);
}
});
});
};
})(jQuery);
where xmlhttp.php is a php file that parses a rss feed.
The question is what am I doing wrong as I am new to both ajax and php.
Thank you very much for your time!
thank you for the datails
its very nice tutorial. thanks a lot.
its awesome tutorial. thanks a lot.
Hi Marijan Šuflaj, i am impress by your skills. I was searching for an easy way to understand ajax in jquery. Finally i found yours. Thanks a lot. It is more than i could ask for.
Blessings
Pinas Delano
It’s a Sexy Bookmarks plugin for WordPress
.
I was wondering where you got your sharing bar, i like it a lot. Or if you made it, how you did.
you did a great work! you did not give us a fish to eat, but you gave us a fishing rod!!
thanks! keep up!
Great tutorial
thanks man!
gj on the tutorial. ty.
Tips, tricks on what?
You could create some controllers that will implement some interface. That interface will have some methods used to return response objects or raw html.
Hi,
Good example. I’m trying to create a page for Add/View/Modify/Delete items. e.g. a form at the top to create new items (say products), below will be paginated set of items already existing with option to edit and delete with simple animated jQuery stuff. Any ideas/tips/tricks?
Use Firebug in firefox (if not install Firebug) to see errors
Found the problem bro, i was using the jquery ui a lot when it wasn’t working. I took it off cuse it was crasing with ie a lot, and it worked fine when I removed all instances of the jquery ui. Then I decided to say fuck IE cuz the it still would display web 2.0 layouts properly and I added the jquery ui back on. Now it’s back to what it was doing before. I seems like it just won’t pass the data along. It won’t serialize or whatever. It keep saying the fields are blank when they are not.
Any suggestions?
Think i got it working, I had this when it was passing empty values
game : $(‘#game’).val(),
I changed it to
game : $(‘#gamename’).val(),
I guess it was picking up the label name as the value or something. Stay tuned.