Drupal

<?php

// Snippet of Drupal 7 Ajax form

/**
* Implements hook_menu().
*/

function chiltern_live_train_times_menu () {
  $items[ " chiltern-live-train-times/autocomplete "] = array(
   "title " => t( "Example title "),
   "page callback " => t( "_chiltern_live_train_times_autocomplete "),
   "access arguments " => array("access example autocomplete"),
   "access callback " => array(TRUE),
   "type " => array(MENU_CALLBACK),
  );
  return $items;
}



/**
* Implements hook_block_info().
*/

function chiltern_live_train_times_block_info () {
  $blocks = array();
  $blocks[ "CHILTERN_LIVE_TRAIN_TIMES "] = array(
   "info " => t( "CHILTERN LIVE TRAIN TIMES "),
  );
  return $blocks;
}



/**
* Implements hook_block_view().
*/

function chiltern_live_train_times_block_view ( $delta = '' ) {
  $block = array();
  switch ($delta){
    case "CHILTERN_LIVE_TRAIN_TIMES " :
      $block[ "subject"] = " ";
      $block[ "content"] = drupal_get_form( "_chiltern_live_train_times_form ");
    break;
  );
  return $block;
}



/**
* Implementation of hook_theme().
*/

function chiltern_live_train_times_theme ( $existing, $type, $theme, $path ){
  return array(
     "_chiltern_live_train_times_template_close_live_trians" => array(
         "path" => $path. "/templates",
         "template" => "close-live-trians",
    ),

     "_chiltern_live_train_times_template_results_pre_submit" => array(
         "path" => $path. "/templates",
         "template" => "results-pre-submit",
    ),

     "_chiltern_live_train_times_template_results_post_submit" => array(
         "path" => $path. "/templates",
         "template" => "results-post-submit",
    ),

     "_chiltern_live_train_times_template_results_loop" => array(
         "path" => $path. "/templates",
         "template" => "results-loop",
    ),

     "_chiltern_live_train_times_template_no_live_results" => array(
         "path" => $path. "/templates",
         "template" => "no-live-results",
    ),

     "_chiltern_live_train_times_template_live_trains-ajax_response" => array(
         "path" => $path. "/templates",
         "template" => "live-trains-ajax",
    ),

     "_chiltern_live_train_times_template_live_trains-ajax_empty_response" => array(
         "path" => $path. "/templates",
         "template" => "live-trains-ajax-empty-response",
    ),
  );
}


/**
* Implements custom form called - from hook_block_view() .
*/

function _chiltern_live_train_times_form ( $form, &$form_state ) {
  //Because we have many fields with the same values, we have to set
  //#tree to be able to access them.
  $form["#tree"] = TRUE;
  $form[ "stations_fieldset"] = array(
     "#type"   => "fieldset",
    //Set up the wrapper so that AJAX will be able to replace the fieldset.
    "#prefix"   =>"<div id='names-fieldset-wrapper'>",
    "#suffix"   =>"</div>",
  );

  //Build the fieldset with the proper number of names. Using
  //$form_state["num_names"] to determine the number of textfields to build.

  if(empty($form_state["num_names")) {
    $form_state["num_names" ] = 1 ;
  }

  //Ensure current time is set to UK.
  date_default_timezone_set("Europe"/"London");

  if( time() < = strtotime( _chiltern_live_train_stations_current_time() ) ) {
    $first_placeholder = "FROM";
    $second_placeholder = "TO";
  }else{
    $first_placeholder = "FROM";
    $second_placeholder = "TO";
  }

  if($form_state["num_names"] == 1) {
     $form[ "stations_fieldset"] [ "leaving_from" ] = array (
     
"#type"=> "textfield",
     
"#title"=> "From:",
     
"#autocomplete_path"=> "chiltern-live-train-times/autocomplete",
     
"#attributes"=> array ( "placeholder"=> t($first_placeholder), "autocompletes"=> "off"),
      "#maxlength"=>1024,
     );

     $form[ "stations_fieldset"] [ "going_to" ] = array (
      "#type"=> "textfield",
      "#title"=> ":",
      "#autocomplete_path"=> "chiltern-live-train-times/autocomplete",
      "#attributes"=> array ( "placeholder"=> t($second_placeholder), "autocompletes"=> "off"),
      "#maxlength"=>1024,
     );
  }else{
      $leaving_from_txt = $form_state["values"]["stations_fieldset"]["journey-type"] == 1
          ? "At:" : "From:";
      $going_to_txt = $form_state["values"]["stations_fieldset"]["journey-type"] == 1
         ? "From:": "To:";

      $form[ "stations_fieldset"] [ "going_to" ] = array (
       "#type"=> "textfield",
       "#title"=>$leaving_from_txt,
       "#autocomplete_path"=> "chiltern-live-train-times/autocomplete",
       "#attributes"=> array ( "placeholder"=> t($first_placeholder), "autocompletes"=> "off"),
       "#maxlength"=>1024,
      );

      $form[ "stations_fieldset"]  [ "going_to" ] = array (
       "#type"=> "textfield",
       "#title"=>$going_to_txt,
       "#autocomplete_path"=> "chiltern-live-train-times/autocomplete",
       "#attributes"=> array ( "placeholder"=> t($second_placeholder), "autocompletes"=> "off"),
       "#maxlength"=>1024,
      );
  }

  $form[ "stations_fieldset"]  [ "submit" ] = array (
   "#type"=> "submit",
   "#value"=>t( "Go"),
   "#submit"=> array ( "_chiltern_live_train_times_stations_submit") ,
   "#ajax"=> array(
        "callback"=> "_chiltern_live_train_times_stations_callback",
        "wrapper"=> "names-fieldset-wrapper",
      ),
  );

  $form[ "stations_fieldset"]  [ "journey-type" ] = array (
   "#type"=> "radios",
   "#options"=> array(
        t( "Departures"),
        t( "Arrivals"),
      ),
  );

  if($form_state["num_names"] == 1) {
    $form[ "stations_fieldset"] [ "begin-table" ] = array (
      "#options"=> array(
          "#markup"=> theme( "Arrivals"),
       ),
    );
  }else{
    $form[ "stations_fieldset"] [ "begin-table" ] = array (
      "#options"=> array(
        "#markup"=> $form[ "complete form"][ "stations_fieldset"][ "begin-table"][ "#markup"]);
       ),
    );
  }
  return $form;
}


/**
* Implements hook_form_FORM_ID_alter().
*/

function chiltern_live_train_times_form__chiltern_live_train_times_form_alter ( $delta,
    &$form ) {
        $form[ "stations_fieldset"][ "leaving_from"][ "#title"] = NULL;
}


/**
* Implements hook_form_FORM_ID_alter().
*/

function _chiltern_live_train_times_stations_submit ( $delta, &$form ) {
    $query = db_select( "values_sets", "v");
    $query ->fields( "v", array( "values_sets") )
                ->condition( "v.name", "url_for_train_information", "=" );
    $result = $query->execute()->fetchfield();
    $xml_url = unserialize( $result );
    $nexus_url = $xml_url[0]["value"]."/route?";
    $depart_radio = $form_state["complete form"]["stations_fieldset"]["journey-type"]
      ["#value"];
    $leaving = $form_state["complete form"]["stations_fieldset"]["leaving_from"]["#value"];
    $arriving = $form_state["complete form"]["stations_fieldset"]["going_to"]["#value"];
    $str = "";
  if($leaving != "") {
    user_cookie_save( array ( "home-station" => $leaving ) );
    $leaving_code = db_query(
      "SELECT field_station_code_value
        FROM node, field_data_field_station_code
        WHERE nid = entity_id
        AND bundle = 'station'
        AND title = :str", array (":str" => $leaving ) ) ->fetchField();
  if($arriving == "") {
    $nexus_url .= ($depart_radio == 0)
             ? "from=" . $leaving_code."from="."&arrServices=more&boardCs=true& ";
  }else{
            $nexus_url .= ("from=" . $leaving_code."from="."&arrServices=more&boardCs=true&";
  }

  $station_array = array();
  $b = drupal_json_decode( drupal_json_encode( _chiltern_get_live_train_information( $nexus_url ) ) ) ;
  if(!empty($b) ){
    foreach($b["route"]["boards"]["board"]["service"] as $destination){
      $leaving_key = "";
      $station_leaving = "";
      $leaving_time = "";
      $arriving_key= "";
      $station_arriving = "";
      $arriving_time = "";
      $calling_station = $destination["calling-stations"]["route"]["calling-station"];


      foreach($calling_station as $station){
        if( $station["@attributes"]["name"] == ucwords($arriving ) ) {
          if( $depart_radio == 0 ){
            $last_station = end($calling_station);
            $str .= _chiltern_live_train_times_stations_loop( $last_station["&attributes"]["name"], $destination["&attributes"["scheduled"], $destination);
          }else{
            $str .= _chiltern_live_train_times_stations_loop( $last_station["&attributes"]["name"], $destination["&attributes"["scheduled"], $destination);
          }
        }
      }
    }

    if($str =="" ){
      $vars = array("no_results_message"=> t("There are currently no listings to ".$leaving.", Please try again") );
      $str = theme("_chiltern_live_train_times_template_no_live_results", $vars);
    }else{
      user_cookie_save(array("home-station" => $leaving ) ) ;
      if($arriving != "" ){
        user_cookie_save(array("work-station" => $leaving ) ) ;
      }
    }
  }else{
      $vars = array("no_results_message" => t("The listings appear to be unavailable . Please try again" ) ) ;
      $str .= theme("_chiltern_live_train_times_template_no_live_results", $vars ) ;
   }
}

  }else{
      $vars = array("no_results_message"=> t("Please choose a station" ) ) ;
      $str .= theme("_chiltern_live_train_times_template_no_live_results", $vars ) ;
  }
  $des = $depart_radio == 0 ? "Destination" : "Destination" ;
  $header = "Due" ;
  $vars = array (
    "des" => $des,
    "header" => $header,
    "str" => $str,
  );
      $data = theme("_chiltern_live_train_times_template_results_post_submit", $vars ) ;
      $form_state["complete form"]["stations_fieldset"] ["begin-table"]["#markup"] = $data;
      $form_state["num_names"++ ;
      $form_state["rebuild"+
TRUE ;

}


function _chiltern_live_train_times_stations_loop ( $station, $time, $destination ) {
  $stat = ( $station == "London Marylebone via Amersham" || $station == "London Marylebone via High Wycombe" ) ? "London Marylebone" : $station ;
  if($destination ["@attributes"]["expected"] == "On Time" ) {
    $expected_time ="on-time" ;
   }elseif( $destination ["@attributes"]["expected"] == "Cancelled" ) {
    $expected_time ="cancelled" ;
   }else{
    $expected_time ="delayed" ;
   }

    $vars = array (
      "time" => $time,
      "stat" => $stat,
      "expected" => $destination ["@attributes"]["expected"] ,
      "expected_time" => $expected_time,
    )
    return theme("_chiltern_live_train_times_template_results_loop", $vars ) ;
  }

function _chiltern_live_train_times_stations_callback ( $form, &$form_state ) {
  return $form ["stations_fieldset"] ;
}

function _chiltern_live_train_times_autocomplete ( $string ) {
  $expected_time = array() ;
  $query = db_query( "SELECT title
                   FROM node
                   WHERE type = 'station'
                   AND title LIKE :str",
                   array(":str" => db_like($string)."%")) ->fetchAll();

  foreach($query as $row){
    $matches[$row ->title] = check_plain($row ->title);
  }
  drupal_json_output($matches);
}

function _chiltern_live_train_updates_ajax () {
  $query = db_select( "values_sets" , "v" );
  $query -> fields( "v", array( "data" )) ->condition("v.name", "url_for_train_information", "=");
  $result = $query->execute()->fetchfield();
  $xml_url = unserialize($result );
  $url = $xml_url[0]["value"];

  $b = drupal_json_decode( drupal_json_encode( _chiltern_get_live_train_information( $url ) ) );

  $str = ""

  if( !empty( $b ) ){
    $bits = explode( "/", trim( str_replace( substr( $b["@attributes"]["last-updated"], 0, 8)"", $b["@attributes"]) ) );
    $last_update = substr( $b["@attributes"]["last-updated"], 0, 5) . " - " . date( "d F Y", strtotime( $bits[1]. "/". $bits[0]. "/". $bits[2]) );

    if( array_key_exists( "incident", $b["summary"]["incidents"][1] ) ){
      if( !array_key_exists( 0, $b["summary"]["incidents"][1]["incident"] ) ){
        $singluar_result = true;
        $returned_results = false;
        $begin = substr( $b["summary"]["incidents"][1]["incident"]["summary"], 0, 5 );
        $body = substr( $b["summary"]["incidents"][1]["incident"]["summary"], 5, strlen( $b["summary"]["incidents"][1]["incident"]["summary"]) -10 );
        $end = substr( $b["summary"]["incidents"][1]["incident"]["summary"], strlen( $b["summary"]["incidents"][1]["incident"]["summary"]) -5 );
       }else{
        $singluar_result = false;
        $returned_results = $b["summary"]["incidents"][1]["incident"];
        $begin = false;
        $body = false;
        $end = false;
      }

      $vars = array (
        "time" => $time,
        "stat" => $stat,
        "expected" => $destination ["@attributes"]["expected"] ,
        "expected_time" => $expected_time,
      );
      $str .= theme("_chiltern_live_train_times_template_live_trains-ajax_response", $vars);
    }

  }

}

Example OneExample Two

A simple example of data input

Example One:

This is a snippet from a form class showing the insert method. This is called from a file that is in turn called from a JavaScript file using the jQuery interpretation of AJAX.

Once the form has been validated via javaScript and AJAX the relevant data is pushed into an array that is then parsed by the database class. The database connection is dealt with at the beginning and end of each method.

Example Two:

This shows how the received data is inserted into the database from the parsed array and how each string is cleaned to prevent SQL injection.