Techblog

Tech Blog

Our latest geek adventures!

2 April Consume SOAP web service from Javascript

Posted by Gert-Jan on in Development, Javascript

I wanted to get some data from a web service using Javascript. I looked at several Javascript classes (like this), but because the web service was running on another server it got a little troublesome. As a solution I tried to call the web service through a proxy, but that didn’t make it any easier.

Jaap suggested to take a look at NuSOAP, a -kinda old- SOAP toolkit for PHP. With an AJAX request I could call a PHP page that uses NuSOAP to consume the web service. It was actually easier then I thought it would be.

To make the AJAX call from Javascript I used Prototype and this script:

  function doRequest() {
    var url = "ajax/consume_webservice.php";
    var param1 = "value1";
    var param2 = "value2";
    var params = "param1="+ param1 +"&param2="+ param2;
 
    new Ajax.Request ( url, { method: 'POST', parameters: params,
      onComplete: onResult } );
  }
 
  function onResult( result ) {
    alert( result.responseText );
  }

The PHP file consume.php looks something like this:

< ?php
 
  $param1 = isset( $POST_['param1'] ) ? $POST_['param1'] : false;
  $param2 = isset( $POST_['param2'] ) ? $POST_['param2'] : false;
 
  // this is the only file I used from the NuSOAP project
  require_once( "nusoap.php" );
 
  $url = webserviceurl;
  $params = array( "param1" => $param1, "param2" => $param2 );
 
  $soap = new nusoap_client( $url, true, false, false, false, false, 0, 60 );
  $proxy = $soap->getProxy();
  $proxy->functionname( $params );
 
  echo $proxy->response;
 
?>

That’s all. Do a AJAX request from Javascript to a PHP page. Then the PHP page uses NuSOAP to consume the web service and returns the result. Back in Javascript you can do whatever you want with the given data.

Tags: , , ,

Leave a Reply