Implementing AJAX in Drupal

In my opinion, the AJAX (Asynchronous javascript and xml) technology has been a real boost to the application of javascript. Traditionally,javascript adds enhancements to a webpage by providing a rich user experience, client-side form validation and submission, and a whole bunch of nifty things:believe me ,javascript is powerful :) A traditional limitation of javascript had been the lack of direct interaction with a server:AJAX to the rescue!Thus,with AJAX, we can query a server for data and add the data to a webpage without reloading the page!Now, that's simply awesome!
The good news is Drupal 6 has native AJAX support. To illustrate this I'll use a form with two textfields in which entering value in one textfield populates the other textfield with a value fetched from a database through AJAX.
Let's assume we have we have a database with a table named color_table, which contains a two columns,'country' and 'color_rep',for a country's color representation (each country has one color).
Now to the form:
function colors_form(){
$path = drupal_get_path('module','mycolors');
drupal_add_js($path.'/color.js');
$form['country'] = array(
'#type'=>'textfield',
'#title'=>t('Name of country')
);
$form['color']=array(
'#type'=>'textfield',
'#title'=>t('Color Representation')
);
$form['submit'] = array(
'#type'=>'submit',
'#value'=>t('Submit')
);
return $form;
}
The above code is a simple form in drupal. First of all, we are implementing this function in a module called mycolors.
The lines that add the ajax(javascript) functionality to this form are:
$path = drupal_get_path('module','mycolors');
drupal_add_js($path.'/color.js');
The first line gets the path of the module in the file system and the second tells drupal to add a javascript file color.js(which we have not yet created), located within the module folder, to the form.
To make a request to the server(and hence our database) for a country's color representation, we need to define a function that handles just that. Here we go :
function colors_form_ajax($country){
$query = "SELECT * FROM {color_table} WHERE country = '%s'";
if($result = db_query($query,$country)){
echo drupal_json(array('response'=>$result->color_rep));
exit;
}
}
The function above does two main things.First, it queries the database,specifically, the color table based on it's argument, and then returns a JSON(Javascript Object Notation) version of the response by calling the inbuilt function drupal_json.
Now that we have the form and the function that queries the server, we ask, how do we link the two? Simple!drupal's menu system.
Lemme delve a bit into the workflow here.
When a user types into the 'Name of country' textfield in our form, the javascript file,color.js, takes the value in the textfield and places a request to a certain menu path,which should then call our 'colors_form_ajax' function,thus returning a JSON version of the response.
So on to our menu:
function mycolor_menu(){
$items = array();
//menu item for our form
$items['colorform'] = array(
'title'=>t('Determine country\'s color'),
'page callback'=>'drupal_get_form',
'page arguments'=>array('colors_form'),
'page arguments'=>TRUE,
'type'=>MENU_NORMAL_ITEM
);
//menu item for the function that queries the database
$items['getcolor/%'] = array(
'page callback'=> 'colors_form_ajax',
'page arguments'=>array(1),
'type'=>MENU_CALLBACK
);
return $items;
}
Some things to note about the code above:
The menu item of the form is denoted to be of the type 'MENU_NORMAL_ITEM'.This means that this menu item will be shown in the navigation block or wherever it's specified to show. The menu item for the function that queries the database on the other hand, is of the type 'MENU_CALLBACK'.This means that this menu will only be called upon request by other parts of the system,as it cannot be seen(and hence clicked) by any user.Also, note the '%' character and the 'page arguments' set to array(1) in the menu definition.It tells drupal to set whichever value,that is appended to the url 'getcolor' to be used as the argument to the function 'colors_form_ajax'.We'll revisit this in the javascript file color.js.
Now to the javascript file.I chose to implement the javascript using jquery, a javascript library, mainly because drupal provides native jquery support and it's cross-platform as well.(You can find more on jquery at http://jquery.com).
The code in our javascript file, color.js looks like this:
Drupal.behaviors.mycolors = function(context){
// when the value in the 'Name of country' textfield changes
$("#edit-country").change(function(){
var chosenCountry = $(this).val();
//function that sets value of the color field when
// a response is obtained
var setColor = function(data){
var response = Drupal.parseJson(data);
$("#edit-color").val(response.color_rep);
}
// path to make the ajax call to
var ajaxPath = 'getcolor/' + chosenCountry;
// making a call to the menu path that will call
// the function that queries the server
$.post(ajaxPath,null,setColor);
return false;
});
});
Here are some things to note about the code above:
The line
Drupal.behaviors.mycolors = function(context)
is equivalent to jquery's $(document).ready() and does the same thing: ensuring that the code fires as soon as the document or 'page' is ready, even though images and other things may not have been loaded completely.
NB: Always remember to follow behaviors with your module's name,mycolors in this case. Leave the 'context' thing untouched.
In drupal, the ids of form elements are preceded by the word edit, so our textfield named country would have the it's id to be edit-country'. Having said that, the next two lines of code get the value entered in the 'Name of country' textfield,anytime the value changes:
$("#edit-country").change(function(){
var chosenCountry = $(this).val();
Next, a function is defined (set to the variable setColor) that parses the response from the server and makes that the value of the 'color' textfield as shown by these lines of code:
var setColor = function(data){
var response = Drupal.parseJson(data);
$("#edit-color").val(response.color_rep);
}
Recall that in the function that queries the server(colors_form_ajax),the $result JSON that was returned had a 'color_rep' attribute,which is referred to in the code snippet above.
We then set the path for the ajax call. Note that this path is the same as the menu path for the function that queries the server for results, and that we add the value in the 'Name of country field' to the path url so that the name will be passed as argument to the function that queries the server as seen in:
var ajaxPath = 'getcolor/' + chosenCountry;
Lastly, we implement the actual ajax call with:
$.post(ajaxPath,null,setColor);
return false;
Note that we passed the second argument as null because we are not sending any separate value. In our case, the value has already been added to the url(ajaxPath).
You should now have a working AJAXified module in drupal!
Cheers.
I just stumbled upon your
I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.
afghanistan trademarks
The inclusion of the
The inclusion of the PHPTemplate and XTemplate engines in Drupal addressed user concerns about flexibility and complexity. The Drupal theming system utilizes a template engine to further separate HTML or CSS from PHP. A popular Drupal contributed module called devel provides GUI information to developers and themers about the page build. Thanks.
professional translational services
nice site
When I first looked at Drupal back in 2002 I’ll admit to being completely unimpressed.Los Angeles SEO
Enables modal functionalities
Enables modal functionalities to your site, using hash information to append it.
Using this hash #modal/hook_menu, you will open in your site, the hook_menu, in a modal, using a theme, selected afer the # caracter. Video Conferencing
Drupal had functions which
Drupal had functions which performed tasks related to databases, such as SQL query cleansing, multi-site table name prefixing, and generating proper SQL queries. In particular, Drupal six introduced an abstraction layer that allowed programmers to create SQL queries without writing SQL. Thanks.
Regards,
website design
I have been awaiting for
I have been awaiting for another excellent post from you. After surfing around your site site web page,Happy to perspective as it is just what you are looking for and energized to study all messages.Werbeagentur
A great informative blog.Keep
A great informative blog.Keep posting articles like.You have a great knowledge of the subject.Thanks for sharing such an article where education of people matters the most.Your way of expressing articles through words is excellent.he way of expressing things is best and informative.Keep sharing articles like this.
huwelijksreizen
good blog
Great to read about it. Thank you for sharing..
Pay For Essay
Persuasive Essays Help
awesome article
Found your web site and decided to use a fast read. The information provided is very very nice and this information is not available so easily. Thanks for sharing .
Tailored Suits
great work
Well that's amazing article! I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
Discount Sportswear | Mens Golf Shirts | Adidas Polo | Izod | Teamwear Football
Nice Info!
Mention my site and I'll tell you what to do to improve the performance of your website. I am happy to give an evaluation of participation and all things related to the Internet. The information is very useful. Writing An Essay ||Essays Help||Write My Essay For Me||Writing Essays For University
Hello,
Profile linkbuilding
High page rank of PR4 to PR6 of forum profile, Angela Paula style at affordable prices.
I discovered your blog site
I discovered your blog site on yahoo and check a few of your early posts. Continue to keep up the very good operate
serrurier bagnolet
Ajax is a group of
Ajax is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously without interfering with the display and behavior of the existing page. Thanks.
Regards,
phone number lookup
Note the new classes being
Note the new classes being added. You’ll need to add these to your css file for your theme. Also the .ajaxStart() function is useful for doing things once a call to the server is being made. Regards, custom university essays
This is a good post. This
This is a good post. This post give truly quality information.I’m definitely going to look into it.Really very useful tips are provided here.thank you so much.Keep up the good works.
Crescent Processing
This is a good post. This
This is a good post. This post give truly quality information.I’m definitely going to look into it.Really very useful tips are provided here.thank you so much.Keep up the good works.
Crescent Processing Company
I somebody been municipality
I somebody been municipality out any of your posts and i can rely pretty groovy move. I cognition definitely bookmark your powerfulness. Machine moulin
All of the contents you
All of the contents you mentioned in post is just too good that will be extremely helpful. I'll ensure that is stays under consideration, thanks for sharing the details keep updating, impatient for more posts
220-701 exam
EX0-101 exam
640-816 exam
70-290 exam
642-902 exam
220-702 exam
SY0-101 exam
70-646 exam
Best part of this post is
Best part of this post is thing: ensuring that the code fires as soon as the document or 'page' is ready, even though images and other things dubai properties | sell dubai properties
Good article
Good article! Thank you so much for sharing this post. Your views truly open my mind. free international calls from mobile | T mobile free calls
This time can be utilized for
This time can be utilized for other important academic or co-curricular activities. However many students unfortunately are not aware of any second option other than forcing themselves to do this daunting work.
Mother's Day Flowers
The post is written in very a
The post is written in very a good manner. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept.
EC0-349 dumps
PK0-002 dumps
PW0-104 dumps
JN0-100 dumps
1D0-435 dumps
9L0-062 dumps
117-201 dumps
1Y0-A09 dumps
Fantastic goods from you,
Fantastic goods from you, man. Ive study your stuff ahead of and you're just as well amazing. I enjoy what you've got right here, adore what you're stating and the way you say it.
professional essay writers
There is so much that you can
There is so much that you can get from this. Being able to use this with drupal is so good. The options are endless for this. orlando short sale
Your post had provided me
Your post had provided me with jQuery and its implications. I had no idea that things can work in this manner as well. Thank you for sharing your perspective. Naturdiet Tom
Your blog provided us with
Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging express news
very nice: search
very nice:
search optimization company | web promotion
Appreciate fantastic blog
Appreciate fantastic blog publish. Where else could I receive this type of information designed in this kind of incite full way. I've got a project that i'm at the moment focusing on, and i'm sure this helps us a lot. and I've been searching for similarly info since from couple of days….Thanks!!!!! Book Report - Thesis Proposal - Research Proposal
fwe
Even if you’re essentially showing full nodes, often you want to tweak a little thing here and there, like add in an image field or hide the date, requiring a jump to fields.PTO pellet mill
I was looking through, much
I was looking through, much too long since the last time I was here There is some stuff. Well just use this one, much appreciated. I need this article for a project, lucky mine has the same subject as this post. I am relieved that I found it, great share. Research Paper - Term Paper
We have to think about it
We have to think about it "Oh, and by the way, you can find our famous "bubble" diagram (shown left) of steel grades there too.
Regards,
Makita Tool Parts
We have to admolished this
We have to admolished this "Here is my comment to show my appreciation to this post. It is just that one I was looking for and I can say I have found it."
Regards,
Buy Power Tools
A comprehensively detailed
A comprehensively detailed and attention grabbing review that you wrote in this article. I am really convinced the way you look. The way you describe the whole thing is simple and understandable
Hopefully what you have
Hopefully what you have talking about that information is right for us..but i am not confused i really feel good here to see the content and development.opening a company in Dubai | business set up Dubai | company formation in Dubai
Hello,I love reading through
Hello,I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts cdl combination vehicles practice test
cdl doubles tripples practice test
cdl general knowledge practice test
cdl hazardous materials practice test
cdl School Bus Practice Test
cdl tank vehicles practice test
Connecticut CDL Practice Test
georgia CDL Practice Test ged language arts practice test Printable GED Practice Test