Drupal 7 Ajax Custom Module Example

This is an example  module that  shows some ideas of what you can do  drupal  ajax in a custom module  I will make a custom auto suggest box with the form api , and has ajax call back with the menu call back , stick that in a custom block, then do some jquery stuff to make it all work.

PRE COMMENT :
I Know I  am breaking some best practices  - but that  fine this is just an example ...
if you understand what I am doing below then you are smart enough to  understand what to do next.

WARNING:  do not this thing on a live site (unless you know what your doing !!) .
This is intended as a get you started .. below makes a custom “auto suggest box ” -
where you can do whatever you want in the ajax call back function.

mymodule.info
name = mymodule
description = Simple Ajex call back function example
core = 7.x
package = Custom

also rember to put a ajax loader image in you module folder


MY MODULE CODE :
mymodule.module

<?php
/**
 * Implements hook_menu().
 * find and replace mymodule !  
 */
function mymodule_menu() { 
	// this example takes 2 arguments 
	// visit yoursite/mymodulepath/arg1/arg2
$items['mymodulepath/%/%'] = array(
    'title' => 'Ajax Page ', // wont be seen 
    'page callback' => 'mymodule_ajax_get_ajax',
    'delivery callback' => 'mymodule_ajax_callback',
    'page arguments' => array(1,2),
    'access arguments' => array('View published content'),
    'type' => MENU_CALLBACK, // not avalable to menus 
  );

  return $items;
}


/* Ajex call back  */

function mymodule_ajax_get_ajax($firstargs , $seccondargs) {
// do stuff 
$output .='<div id="closeme">X</div>';
$output .='First Argument is'.$firstargs;
$output .='<br/>Seccond Argument is'.$seccondargs;

// run what ever php you want 
$output .='<br/><span class="childelle">CLICK TO SET</span>';

return $output; 
}

// callback 
function mymodule_ajax_callback($page_callback_result) {
	
// php only - this is automaticly  gitting passed the $output var from above 
echo $page_callback_result;

}

// basic form 
function mymodule_form($form, &$form_state) {
$form['#attributes']['autocomplete'] = 'off';
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('A simple form '),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#id' =>'MYID',
    '#suffix' => '<div id="lodespot"></div>',

  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

// submit handeler 
function mymodule_form_submit($form, &$form_state) {
$name = $form_state['values']['name'];
drupal_set_message(t('You submited'.$name), 'status',TRUE);
}


// block to display form 

/**
 * Implementation of hook_block_info().
 */
function mymodule_block_info() {
  $blocks['mymoduleblock'] = array(
    'info' => t('Simple Block'),
  );
  return $blocks;
}
 
/**
 * Implementation of hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'mymoduleblock':
      $block['subject'] = t('Simple Block');
      $block['content'] = mymodule_blockfunction_contents();
      break;
  }
  return $block;
}
 
/**
 * custom html block
 * @return string
 */
function mymodule_blockfunction_contents() {

$output ='top html stuff <br/>';

$output .= mymodule_jquerystuff(); 
// get the form 
$form = drupal_get_form('mymodule_form');
$output .= render($form);
  return $output ;
}

// custom jquery stuff 
function mymodule_jquerystuff(){
	// i know this put in a css file just example :)

	$output ='
<style type="text/css">
#lodespot{
	background: none repeat scroll 0 0 #fff;
    border: 1px solid;
    min-height: 10px;
    padding: 10px;
    position: absolute;
    z-index: 5;
    display: none;
    color:#000;
    margin-top:-10px;

}

#lodespot #closeme{
 background: none repeat scroll 0 0 #000;
    border: 1px solid;
    border-radius: 8px;
    float: right;
    font-size: 8px;
    height: 11px;
    padding: 2px;
    color: #fff;
    margin-left: 88px;
}


</style>';

// jquery stuff !

 $output ='<script>
    (function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    //code starts
 
 $.ajaxSetup ({
		cache: false
});

// the load 
$("#MYID").keyup(function(){
var thestring = $("#MYID").val(); 

 // string to array for spaces seems to break ?
var myArray = thestring.split(" ");

var ajax_load_img = "<img src=\''.$GLOBALS['base_url'].'/'.drupal_get_path('module', 'mymodule').'/ajax-loader.gif\' alt=\'loading...\' />";

var loadUrl = "'.$GLOBALS['base_url'].'/mymodulepath/arg1/"+myArray;

if(thestring.length > 2 ){
	//alert(myArray);
$("#lodespot").html(ajax_load_img).load(loadUrl);
$("#lodespot").show();
}

}); // end keyup function

// the value set from returned <span class="childelle">WHAT IS IN HERE</span>
$("#lodespot").on("click", ".childelle", function() { 
	var chvalue = $(this).html();
	alert(chvalue);
	$("#MYID").val(chvalue);
// hide the box 
	$("#lodespot").html();
	$("#lodespot").hide();
});

// close box 
$("#lodespot").on("click", "#closeme", function() {
	$("#lodespot").html();
	$("#lodespot").hide();
});

    //code ends
  }
};
})(jQuery);
    </script>';
return $output;
}

?>