Send data and read JSON string from URL (HTTP Request)

Some time ago I need to creating a Webform where visitors need to fill in the data required before they can download a specific file.

So the order is as follows:

  1. Send data to the server such as name, email, company, etc. (site A and site B has different server).
  2. Read the string given by the server in the form of JSON. The given string is a place where we can download the file.

Examples of JSON string:

{"success":true,"downloadUrl":"http://www.example.com/webfiles/example.exe"}

As usual, I use Drupal, and using the Webform module.

To be much faster, I just changed the webform-confirmation.tpl.php and named according to the ID of the webform (eg webform-confirmation-1.tpl.php) and put it in the theme folder that is used. Here is the code:

$submission_data = webform_menu_submission_load($sid, $node->nid);
 $url = 'http://www.example.com/download.php?';
 $data = array (
  'manager' => $submission_data->data[1]['value'][0],
  'email' => $submission_data->data[2]['value'][0],
  'company' => $submission_data->data[3]['value'][0],
  'country' => $submission_data->data[4]['value'][0],
  'model' => $submission_data->data[5]['value'][0],
  'feature' => $submission_data->data[6]['value'][0],
  'srlnbr' => $submission_data->data[7]['value'][0],
  'prodid' => $submission_data->data[8]['value'][0]
 );
 $query = http_build_query($data, '', '&');
 $f_url = $url . $query;
 $content = file_get_contents($f_url);
 $json = json_decode($content);
 $dl = $json->{'downloadUrl'};
 if ($dl == '') {
  // null
 }
 else {
  header('Refresh: 3; URL=' . $dl);
 }

With the solution above, we do not need to use JavaScript / jQuery. We could also use drupal_http_request(); but more effective using above methods because I need to read the JSON string also.


Author: danpros

A self-proclaimed geek, business owner, and part-time blogger.

Comments on “Send data and read JSON string from URL (HTTP Request)”