serving the solutions day and night

Pages

Friday, June 11, 2010

AJAX, Send XML Request/Response Using PHP XML DOM - Part 3

I blogged What Ajax is and higher-level codes, let's put all together and example for send XML request/response using Ajax enabled PHP application.

Here i explain 2 application of XML.
1)To send a request from a Ajax to a PHP in XML format.
2)To receive a response from a PHP in Ajax in XML format.


View Sequence Diagram for AJAX
View AJAX Flow Diagram

GetXmlHttpObject() function used to created and configured a XMLHttpRequest object.
function GetXmlHttpObject()
{
  var objXMLHttp=null;
  if (window.XMLHttpRequest) objXMLHttp=new XMLHttpRequest();
  else if (window.ActiveXObject) objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  return objXMLHttp;
}

createXML() function is used to create a XML document, just stringing together the text. value pairs turn into XML elements, where the element <name> is the name of the pair, and the content of the element is the value, like <coinid>123</coinid>.
function createXML( root, nodes )
{
  var xml = "";
  if( root )
    xml += "<" + root + ">";
  for( theNode in nodes )
    xml += "<" + theNode + ">" + nodes[theNode] + "";
  if( root )
    xml += "";
  return xml;
}

Much of the below statements are self-explanatory.
SingleIUD() function executes
1)Collects the form input value.
2)Creats an xml document.
3)Create an XMLHttpRequest object.
4)Create the function to be executed when the server response is ready.
5)Send the request to the php file on the server.
6)Receive xml document response from the php file on the server and.
7)Finally parse the xml document.
var xmlCoin;
function SingleIUD()
{
  var coinid = document.getElementById('coinid').value;
  var dml = document.getElementById('dml').value;
  var amount = document.getElementById('amount').value;
  var desc = document.getElementById('desc').value;

  var params = {};
  params["coinid"] = coinid;
  params["dml"] = dml;
  params["amount"] = amount;
  params["desc"] = desc;

  xml = createXML("coin",params);
  xmlCoin=GetXmlHttpObject()
  if (xmlCoin==null)
  {
    alert ("Browser does not support HTTP Request");
    return;
  }

  var url = "ajcoindml.php?sid="+ Math.random();
  xmlCoin.onreadystatechange=function()
  {
    if (xmlCoin.readyState==4 || xmlCoin.readyState=="complete")
    {
      var xml = xmlCoin.responseXML.documentElement;
      var coinid = (xml.getElementsByTagName("coinid")[0]).childNodes[0].nodeValue;
      var dml = (xml.getElementsByTagName("dml")[0]).childNodes[0].nodeValue;
      var error = (xml.getElementsByTagName("error")[0]).childNodes[0].nodeValue;
      //Your business logic script
    }
  };
  xmlCoin.open("POST",url,true)
  xmlCoin.send(xml);
}

When the AJAX is sent request to the PHP file,
1)PHP receive xml document request.
2)Parse xml document using DOM object.
3)Create a response xml docment.
4)Send response xml document back to the AJAX XMLHttpRequest object.
The request is processed by the ajcoindml.php. Here i used PHP XML DOM, compare to SAX, DOM has an in-memory tree structure, provide to modify an XML document. The DOM XML parser functions are part of the PHP core, no installation needed to use these functions.

find_node_value_xml() function contains
1)Initialize and creates a DOM Document object.
2)Load the xml.
3)Loop through all elements of the element:
4)Find the node value of the element and return it.
<?php
  header('Content-Type: text/xml; charset=utf-8');

  $iappid = "1";
  $xmldata = file_get_contents('php://input');
  $sxml = "";
  $serror = "";
  $icoinid= "";

  if (!empty($xmldata))
  {
    $icoinid= find_node_value_xml($xmldata, "coin", "iappid", $iappid, "coinid");
    $sdml = find_node_value_xml($xmldata, "coin", "iappid", $iappid, "dml");
    $damount= find_node_value_xml($xmldata, "coin", "iappid", $iappid, "amount");
    $sdesc = find_node_value_xml($xmldata, "coin", "iappid", $iappid, "desc");

    //Your business logic goes here.

    $sxml.="<response><coinid>". $icoinid. "</coinid>";
    $sxml.="<error>". $serror. "</error></response>";
    echo $sxml;
  }

  public function find_node_value_xml($xml, $node, $tag1, $tagval1, $tag2)
  {
    $tag2_value ="";
    $domdoc = new DomDocument('1.0');
    $domdoc->loadxml($xml);
    $tag = $domdoc->getElementsByTagName($node);
    $xmltag=0;
    foreach( $tag as $tags )
    {
      $tag_name = $tags->getElementsByTagName($tag1);
      $tag_value = $tag_name->item(0)->nodeValue;
      if ($tag_value==$tagval1)
      {
        $tag2_name = $tags->getElementsByTagName($tag2);
        $tag2_value = $tag2_name->item(0)->nodeValue;
        break;
      }
    }
    return $tag2_value;
  }
?>
The ajcoindml.php returns an XML document containing the results. Following a successful request, the object returns of the XML document that was retrieved from the ajcoindml.php using the xmlCoin.responseXML;

<response>
  <coinid></coinid>
  <error></error>
</response>
The statment (xml.getElementsByTagName("coinid")[0]).childNodes[0].nodeValue; is used to parse XML response.

Ajax (Asynchronous JavaScript and XML) - Part 1
AJAX, Send/Receive XML Request/Response using JAVA - Part 2

2 comments:

Mustafa Kahraman said...

Wht you don't use someting like jquery ? It's more easy and powerful ;)

Daynight said...

Compare to jquery, this is more simple and easy to write. For jquery you have to install jquery javascript, and understand about the functions and flow. This is also another way of AJAX and PHP communication