« Grand River Interactive is hiring an interface engineer in Ann Arbor, MI

Using CSS specificity to better organize your JavaScript »

Sending an XML document object to PHP with jQuery

June 10th, 2009 by Brian | 12 Comments »

The most common approach to passing data to PHP with jQuery’s Ajax implementation is to post query string parameters as key/value pairs. These values are read by your application, and then a response is typically constructed by the server-side, informing the client-side of the results. However, there is another approach that is often overlooked, and that is passing a full-blown XML document object to the server.

There is little mention of this in the official documentation, which makes it difficult to construct a working example. The approach does have several advantages, including the ability to use remote procedure calls via XML-RPC on the client-side. For instance, in Magento Commerce there is already a services API that you could connect to from jQuery to read catalog, customer or product data. All you would need to do is pass across an XML document that adheres to the XML-RPC specification.

The alternative is creating a hook that accepts an XMLHttpRequest, which then calls the API, and then returns a response. You are able to bypass this step by using jQuery’s built-in ability to send an XML document object with the .ajax() function.

Creating an XML document client-side

The first step is to create an XML document on the client-side that can be passed along in the request. I will take direction from the createXMLDocument plugin. This is fairly straightforward.

jQuery.createXMLDocument = function( s ) {
	var browserName = navigator.appName;
	var xmlDoc;
	if ( browserName == "Microsoft Internet Explorer" ) {
		xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
		xmlDoc.async = "false";
		xmlDoc.loadXML( s );
	} else {
		xmlDoc = ( new DOMParser() ).parseFromString( s, "text/xml" );
	}
	return xmlDoc;
}

The function takes a string as an argument, which should be a string representation of an XML schema. What will be returned back is an XML document object.

Create your XML and build your Ajax function

$(function() {
	var xmlDoc = jQuery.createXMLDocument( "<items></items>" );
	jQuery( "items", xmlDoc ).append( jQuery( "<item>Hello World!</item>" ) );
	jQuery.ajax({
		url: "your-server-side-script.php",
		type: "POST",
		processData: false,
		contentType: "text/xml",
		data: xmlDoc,
		success: function( data ) {
			alert( data );
		}
	});
});

Here are a few important points to remember with this little snippet:

  • After creating your XML document, the way to append nodes is to use jQuery as an object wrapper in the method. If you try to append a string as a node to an XML document it does not appear to work.
  • The processData parameter must be set to false. If you do not do this, then any data sent will be interpreted as a string, no matter how you set your contentType.
  • Your contentType must be “text/xml”.
  • All the success function will do at this point is alert what the PHP sends back in the response. If you were making a remote procedure call, you could set up a wrapper to handle the specially formatted XML response according to the XML-RPC specification.

Process an XML POST request from your PHP script

If you have never tried this before, then the whole process might appear confusing at first glance. Because you’re not sending POST variables, but an actual XML document, then you can’t use the $_POST predefined variable. You will have to use $HTTP_RAW_POST_DATA to get your XML, or the less memory intensive file_get_contents( “php://input” ), which is an input stream.

$xml = file_get_contents( "php://input" );
$simpleXml = simplexml_load_string( $xml );
$simpleXml->xpath( "/items/ITEM" );
foreach ( $simpleXml as $item ) {
	echo $item . "\n";
}

This is self-explanatory, but there is a small glitch that I need to mention. Notice how the ITEM node in the XPath expression is uppercase? The Mozilla Developer Center provides the best explanation:

“In XML (and XML-based languages such as XHTML), tagName preserves case. In HTML, tagName returns the element name in the canonical uppercase form. The value of tagName is the same as that of nodeName.”

The internals of jQuery on a DOM node insertion do not reconcile the uppercase form, and so when you search for a node by expression you need to be aware of this. Now that you know that little tidbit you are one step closer to using XML as your primary data interchange format across the board.

Edit 7/17/09: I was just reading over this again and realized I hadn’t swapped the less than/greater than signs with their html entity counterparts. Sorry about that for those that were confused!

Tags: , , ,

Posted in: JavaScript, PHP, Web Development

This entry was posted on Wednesday, June 10th, 2009 at 7:23 pm and is filed under JavaScript, PHP, Web Development.

You can follow any responses to this entry through the RSS 2.0 feed.

Both comments and pings are currently closed.

12 Responses to “Sending an XML document object to PHP with jQuery”

  1. pfwd says:

    Good article. I will have to try this.

  2. [...] Brian Reindel tells us about Sending an XML document object to PHP with jQuery. [...]

  3. Mario Z. says:

    Very good post !
    I was confronted with the need to do exactly this some months ago, but didn“t have the time and knowledge to get it right !
    As a shortcut, we created the XML as a long string, escaped it, copied it to a textarea inside a form, and POSTed it in the regular way. NOt as elegant, but it worked.
    But the solution you present here is the “right” choice !

  4. theodin says:

    great article, this is a real eye opener for me, thanks for sharing!

  5. gunasekaran says:

    Dear sir I have post the xml object please Let you know how will i have get the xml object with information in server side PHP

    Example of ASP

    Dim objXml
    set objXml = createObject(ms2xml.DomDocument)
    objXml.load(Request)

    I need PHP examples

  6. Brian says:

    @gunasekaran

    Please review the post under the subheading “Process an XML POST request from your PHP script”

  7. Hard to believe you can’t glean this from the JQuery doc. Thanks so much.

  8. Meta says:

    Great article, many thanks.

  9. Rob L says:

    Is it just me or does this not work in IE8?

    I get ‘type mismatch’ errors on the line…
    jQuery( “items”, xmlDoc ).append( jQuery( “Hello World!” ) );

  10. Brian says:

    Hi Rob,

    I will test in IE8.

    Brian

  11. Tom says:

    Wow great post Brian,
    this is something that will really help me in a project where much data (nested arrays) is being sent to the server and key/value is just not enough. I cant believe how elegant is this solution.
    Thanks much!

  12. [...] Brian Reindel tells us about Sending an XML document object to PHP with jQuery. [...]