Drupal API: drupal_http_request()

Often times 1 website needs to communicate with another service provider or simply fetch remote data periodically (such as via an AJAX button on an HTML form).

If you’re just coding vanilla PHP and your server has the required extension then PHP CuRL is your best friend.

Drupal core API has a helpful utility function drupal_http_request() to perform basic HTTP web requests: GET, POST, PUT, etc and following redirects if any are found.

Recently I wired-in the use of this function to a Drupal Ajax Form. The most pertinent nuts and bolts are as follows from my custom questionaire_4d_selector.module file:

function questionaire_4d_selector_form_ajax_callback($form, $form_state) {
  $questionaire_id = $form_state['values']['questionaire_id'];
  // If the form has errors we show them in the Preview spot. There's not much
  // else we can do because jQuery is replacing out the specified target element
  // in the #ajax FAPI element.
  if (form_get_errors()) {
    return $form['preview-content-area']['esci-questionaire'];
  }
  $remote_response = retrieve_questionaire_4d_response($questionaire_id);
  if (strpos($remote_response->data, 'Error',0) === 0) {
    form_set_error('questionaire_selector', "<b>Remote 4D Error</b><br>" . $remote_response->data);
    return $form['preview-content-area']['esci-questionaire'];
  }
  if ($questionaire_id) {
    $form['preview-content-area']['esci-questionaire']['#markup'] = questionaire_4d_selector_build_esci_questionaire_preview($questionaire_id, $remote_response->data);
  }
  // If everything is ok -- simply tell the Ajax framework what we're replacing out.
  return $form['preview-content-area']['esci-questionaire'];
}

function questionaire_4d_selector_form($form, &$form_state) {
 // for ajax form state inspection goto file in /tmp directory.
 dd($form_state);
 //dpm($form_state);

  $form_passed_get_parameter_questionaire_id = $form_state['submitted'] == FALSE &&
          count($form_state['build_info']['args']) &&
          ctype_digit($form_state['build_info']['args'][0]);
//dpm($form_passed_get_parameter_questionaire_id ? 1 : 0);
  if ($form_passed_get_parameter_questionaire_id) {
    $id = $form_state['build_info']['args'][0];
  } else {
    $id = !empty($form_state['values']['questionaire_id']) ? $form_state['values']['questionaire_id'] : '';
  }
//dpm($id);
  $form['questionaire_selector'] = array(
    '#type' => 'fieldset',
    '#title' => t('Select 4D Questionaire'),
  );
  $form['questionaire_selector']['access_id'] = array(
    '#type' => 'hidden',
    '#value' => drupal_get_token(QUESTIONAIRE_4D_PREVIEW_AJAX_SECRET_VALUE),
  );
  $form['questionaire_selector']['questionaire_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Questionaire Number'),
    '#default_value' => $id,
    '#element_validate' => array('element_validate_integer_positive'),
    '#size' => 15,
  );
  $form['questionaire_selector']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Preview 4D Questionaire'),
    '#ajax' => array(
      'callback' => 'questionaire_4d_selector_form_ajax_callback',
      'wrapper' => 'questionaire-preview',
      'method' => 'replace',
    ),
  );
  $form['preview-content-area'] = array(
    '#type' => 'fieldset',
  );
  $form['preview-content-area']['esci-questionaire'] = array(
    '#prefix' => '<div id="questionaire-preview">',
    '#suffix' => '</div>',
    '#type' => 'markup',
    '#markup' => '<h3>Your Questionaire Preview will appear here.</h3>',
  );

  if ($form_passed_get_parameter_questionaire_id) {
    $remote_response = retrieve_questionaire_4d_response($id);
    if (strpos($remote_response->data, 'Error',0) === 0) {
      form_set_error('questionaire_selector', "<b>Remote 4D Error</b><br>" . $remote_response->data);
    }
    $form['preview-content-area']['esci-questionaire']['#markup'] = questionaire_4d_selector_build_esci_questionaire_preview($id, $remote_response->data);
  }

  $form['#attached']['css'] = array(
    drupal_get_path('module', 'questionaire_4d_preview') . '/assets/questionaire_4d_preview.css',
  );
  return $form;
}

function retrieve_questionaire_4d_response($questionaire_id) {
  $url = QUESTIONAIRE_4D_PREVIEW_4D_SERVICE_URL;
  $data = array('varQFormID' => $questionaire_id);
  $full_url = url($url, array('query' => $data));

  return drupal_http_request($full_url);
}

This code has 3 major functions. The form builder function that builds a $form object for Drupal to show. 1 button on the form contains an #ajax element the when pressed does our ajax callback. The callback functions basic job is to define the area of the original $form which is to be re-built seamlessly via Ajax. It also calls our remote URL using drupal_http_request() as an Ajax action.

The form builder function builds the form when first seen by the visitor. This same Ajax button is allowed to be populated by a simple GET request to this Drupal page. If an ID for an item is passed to this page — when the form is being built for the user on their 1st visit the page use drupal_http_request() to attempt to load the page as if the user had made an Ajax request.

As you can see Drupal provides many useful APIs out-of-the-box for general web tasks. If these don’t meet your needs there are other contributed modules such as background_process or the HTTP Parallel Request and Threading Library or the Web Services Client module.

Looking for quality Drupal Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , | Posted under Drupal | RSS 2.0

Author Spotlight

David Gurba

David Gurba

I am a web programmer currently employed at UCSB. I have been developing web applications professionally for 8+ years now. For the last 5 years I’ve been actively developing websites primarily in PHP using Drupal. I have experience using LAMP and developing data driven websites for clients in aviation, higher education and e-commerce. If you’d like to contact me I can be reached at david.gurba@arvixe.com

Leave a Reply

Your email address will not be published. Required fields are marked *


7 + = 12

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>