Data availability using ajax: I was going for an interview where I had clear my first round and in the second round they had given me a form in this which lots of functionality with ajax validation of data in the database. So had stat my coding test and stuck at a point where I have to do this so I had searched about this and find the best solution. Actually this solution I have found in a contributed module called "Username check" but this module only works for username field on the registration form in Drupal but I have to use same functionality for other fields so I had added this functionality with my custom form to achieve my requirement. Here is the code for this.
First, create a custom module so go to your project directory->sites->all->modules here you have to create 2 folders named "Contrib" and "Custom".
Contrib: Where you put all contributed module in it.
Custom: Where you create all custom module in it.
In custom module create a folder called form_test2 and then "form_test2.info, form_test2.module, ajax_validation.inc and a form_test2.js (in js folder)" files in it. Now open form_test2.info file and put this code in it.
name = form test 2
description = Custom form for client site validation.
core = 7.x
package = Custom
files[] = form_test2.module
Now Open the form_test2.module file and follow these steps 1. create menu path for custom form and JQuery data validation.
/**
*Implement hook_menu()
*/
function form_test2_menu() {
$items['formtest2'] = array(
'title' => 'Ajax check',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test2_form'), //call custom form
'access callback' => TRUE,
'type'=> MENU_NORMAL_ITEM,
);
$items['formtest2/availability'] = array(
'page callback' => 'availibility_test',
'access arguments' => array('administer site configuration'),
'file' => 'ajax_validation.inc',
'type'=> MENU_CALLBACK,
);
return $items;
}
2. Now create a custom form with submit handler.
/**
*Implement hook_form()
*/
function form_test2_form($form,&$form_submit) {
_form_test2_load_resources(); //function return JS and set path to drupal behavior.
$form['firstname'] = array(
'#title' => t('Firstname'),
'#type' => 'textfield',
'#required' => TRUE,
'#suffix' => '',
);
$form['lastname'] = array(
'#title' => t('Lastname'),
'#type' => 'textfield',
'#required' => TRUE,
'#maxlength' => 20,
);
$form['email'] = array(
'#title' => t('Email'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['submit'] = array(
'#value' => 'Submit',
'#type' => 'submit',
);
return $form;
}
//Submit handler to form_test2_form() function
function form_test2_form_submit($form,&$form_submit) {
drupal_set_message("hello", "warning");
}
//add JS and set path to Drupal behavior
function _form_test2_load_resources() {
$module_path = drupal_get_path('module', 'form_test2');
drupal_add_js($module_path . '/js/form_test2.js', array('weight'=>1001, 'scope'=>'footer'));
drupal_add_js(array( 'usernameCheck' => array(
'ajaxUrl' => url('formtest2/availability', array('absolute' => TRUE)),
),
), 'setting');
}
From the above code, we are using a drupal_add_js function in which we are adding custom path "formtest2/availability" to js Drupal behavior. On this path, we have called an ajax_validation.inc file to call "availibility_test" function which we already mention this to our form_test2_menu function. Later we will use this variable in our js file.
drupal_add_js(array( 'usernameCheck' => array(
'ajaxUrl' => url('formtest2/availability', array('absolute' => TRUE)),
),
), 'setting');
3. Now create a folder called JS in your module folder and create a custom JS file called form_test2.js in it for validation handler and put this code in it.
(function($) {
$("#edit-firstname").blur(function() {
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post(Drupal.settings.dataCheck.ajaxUrl,{ user_name:$(this).val() } ,function(data){
if(data=='no'){
//if username not avaiable
$("#msgbox").fadeTo(200,0.1,function() {
//start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
$("#edit-firstname").focus();
});
} else{
$("#msgbox").fadeTo(200,0.1,function(){
//start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
})(jQuery);
4. Now create custom .inc file called ajax_validation.inc which will return data called by ajax validation function.
function availibility_test(){
if(isset($_POST['user_name'])) {
$username = mysql_real_escape_string($_POST['user_name']);
if(!empty($username)) {
$result = db_select('users','u')
->fields('u', array())
->condition('name', $username, '=')
->execute()
->fetchObject();
if($result->name) {
echo 'no';
} else{
echo 'yes';
}
}
}
}