Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Project jQuery
Purpose
The purpose of this tutorial is to show, with full and working examples (using JQuery version 1.9 and AJAX), how to read, send and receive XML, SOAP-XML and JSON. As well, how to use basic authentication will be illustrated (in some scenarios it may be useful but, as an old protocol, may not be an excellent solution).

The first half of examples are XML based going from reading XML to sending/receiving XML and SOAP to sending/receiving XML with basic authentication. The last half of examples are JSON based and follow the same flow.

READ XML [Download Zip Example]
JAVASCRIPT CODE

<html>
<head>
<script src="jquery-1.9.1.js" language="text/javascript" type="text/javascript"></script>
<script language="text/javascript" type="text/javascript">

// Wrap everyting in this READY directive
$(document).ready(function () {

	//alert( 'You are running jQuery version: ' + $.fn.jquery );

	// When the button is clicked perform the AJAX request
	$('#trigger').click(function() {
		$('#userMsg').text("Loading XML data..."); // update status of AJAX call

		/* Define AJAX Settings */
		var ajaxURL = "ajax.xml";
		var ajaxType = "GET";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "xml";
		var ajaxContentType = "application/x-www-form-urlencoded; charset=UTF-8";
		var ajaxAsynchronous = true;
		var ajaxCache = false;
		var ajaxCrossDomain = false;
		var ajaxDataToTarget = "";
		var ajaxUseGlobalHandlers = false;
		var ajaxUsername = "";
		var ajaxPassword = "";
		var ajaxTimeout = 5000;

		var haveRootNodeTag = "Collection";
		var haveChildNodeTag = "Book";

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text xml": jQuery.parseXML}					/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
		        ,data: ajaxDataToTarget								/* Data to send to the target which is appended to the URL for GET requests as name/value pairs like { name: "John", location: "Boston" } or XML like var xmlDocument = [create xml document here]; declared outside the block of code and data: having a value of xmlDocument */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    /* Go through the root node */
				    $(data).find(haveRootNodeTag).each(function() {
										   haveExpectedFormat = 1;
										   /* Iterate through each child node */
										   $(this).find(haveChildNodeTag).each(function() {
																   /* Grab the element title and attribute */
																   haveExpectedResponse = 1;
																   alert("Title = " + $(this).find("Title").text() + "\nAttribute Value = " + $(this).find("Title").attr("RenderAs"));
																  } /* End Function */
														       ); /* End Each */
										   } /* End Function */
								    ); /* End Each */
				   } /* End Function */
		   )
	      .fail(
		    function(data) { $('#userMsg').text("Loading XML data response failed with >> " + data.statusText + "."); }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received an XML response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("XML was returned but not in the expected format.");
												     }
								     else { $('#userMsg').text("Loading XML data response completed."); }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     }
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

}); /* End document.ready */

</script>
</head>
<body>
Get some XML data from an external source.  <input type="button" value="Click Here" id="trigger" /> <div id="userMsg" />
</body>
</html>

XML USED

<?xml version="1.0" encoding="utf-8" ?>
<Collection>
  <Book>
     <Title RenderAs="html">Book number 1</Title>
     <Publisher>Pub1</Publisher>
  </Book>
  <Book>
     <Title RenderAs="ascii">Book number 2</Title>
     <Publisher>Pub2</Publisher>
  </Book>
  <Book>
     <Title RenderAs="email">Book number 3</Title>
     <Publisher>Pub3</Publisher>
  </Book>
  <Book>
     <Title RenderAs="text">Book number 4</Title>
     <Publisher>Pub4</Publisher>
  </Book>
</Collection>


SEND XML WITH POST [Download Zip Example]
JAVASCRIPT CODE

<html>
<head>
<script src="jquery-1.9.1.js" language="text/javascript" type="text/javascript"></script>
<script language="text/javascript" type="text/javascript">

// Wrap everyting in this READY directive
$(document).ready(function () {

	//alert( 'You are running jQuery version: ' + $.fn.jquery );

	// When the button is clicked perform the AJAX request
	$('#trigger').click(function() {
		$('#userMsg').text("Sending XML data..."); // update status of AJAX call

		/* Define AJAX Settings */
		var ajaxURL = "server-processing.aspx";
		var ajaxType = "POST";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "xml";
		var ajaxContentType = "application/x-www-form-urlencoded; charset=UTF-8";
		var ajaxAsynchronous = true;
		var ajaxCache = false;
		var ajaxCrossDomain = false;
		var ajaxDataToTarget = encodeURIComponent("<Info><Item><Title>Great Item</Title><Description>A great item that should be added.</Description></Item></Info>");

		var ajaxUseGlobalHandlers = false;
		var ajaxUsername = "";
		var ajaxPassword = "";
		var ajaxTimeout = 5000;

		/* Handle XML Response (in this example just getting back the XML that was sent to the server) */
		var haveRootNodeTag = "Info";
		var haveChildNodeTag = "Item";

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text xml": jQuery.parseXML}					/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
		        ,data: ({datasnd: ajaxDataToTarget})						/* Data to send to the target which is appended to the URL for GET requests as name/value pairs like { name: "John", location: "Boston" } or XML like var xmlDocument = [create xml document here]; declared outside the block of code and data: having a value of xmlDocument */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    /* Go through the root node */
				    $(data).find(haveRootNodeTag).each(function() {
										   haveExpectedFormat = 1;
										   /* Iterate through each child node */
										   $(this).find(haveChildNodeTag).each(function() {
																   /* Grab the element name and description */
																   haveExpectedResponse = 1;
																   alert("Title = " + $(this).find("Title").text() + "\nDescription = " + $(this).find("Description").text());
																  } /* End Function */
														       ); /* End Each */
										   } /* End Function */
								    ); /* End Each */
				   } /* End Function */
		   )
	      .fail(
		    function(data) {
				    $('#userMsg').text("Loading XML data response failed with >> " + data.statusText + ".");
				   }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received an XML response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("XML was returned but not in the expected format.");
												     }
								     else { $('#userMsg').text("Loading XML data response completed."); }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     }
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

}); /* End document.ready */

</script>
</head>
<body>
Send some XML data to an external source and get a response.  <input type="button" value="Click Here" id="trigger" /> <div id="userMsg" />
</body>
</html>

XML USED

<?xml version="1.0" encoding="utf-8" ?>
<Info>
	<Item>
		<Title>Great Item</Title>
		<Description>A great item that should be added.</Description>
	</Item>
</Info>


AUTHENTICATE TO SITE, THEN SEND XML WITH POST [Download Zip Example]
JAVASCRIPT CODE

<html>
<head>
<script src="jquery-1.9.1.js" language="text/javascript" type="text/javascript"></script>
<script language="text/javascript" type="text/javascript">

// Wrap everyting in this READY directive
$(document).ready(function () {

	//alert( 'You are running jQuery version: ' + $.fn.jquery );

	// When the button is clicked perform the AJAX request
	$('#trigger').click(function() {
		$('#userMsg').text("Authenticating and Sending XML data..."); // update status of AJAX call

		/* Define AJAX Settings */
		var ajaxURL = "https://www.yoursite.com/site-folder-with-authentication-set-on-it/server-processing.aspx";
		var ajaxType = "POST";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "xml";
		var ajaxContentType = "application/x-www-form-urlencoded; charset=UTF-8";
		var ajaxAsynchronous = false;
		var ajaxCache = false;
		var ajaxCrossDomain = false;
		var ajaxDataToTarget = encodeURIComponent("<Info><Item><Title>Great Item</Title><Description>A great item that should be added.</Description></Item></Info>");

		var ajaxUseGlobalHandlers = false;
		/* Under windows server, a folder was setup with basic authentication on it.  Then a local user account (created on the server) was created and then given permissions to the folder.  NOTE: a domain account could be used as well. */
		var ajaxUsername = "test";
		var ajaxPassword = "tester";
		var ajaxTimeout = 5000;

		/* Required for Basic Authentication (HTTP 401 Challenge); jQuery not able to perform basic authentication with native .username and .password parameters */
		var basicAuthData = "";
		basicAuthData = "Basic " + btoa(ajaxUsername + ":" + ajaxPassword);

		/* Handle XML Response (in this example just getting back the XML that was sent to the server) */
		var haveRootNodeTag = "Info";
		var haveChildNodeTag = "Item";

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text xml": jQuery.parseXML}					/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
		        ,data: ({datasnd: ajaxDataToTarget})						/* Data to send to the target which is appended to the URL for GET requests as name/value pairs like { name: "John", location: "Boston" } or XML like var xmlDocument = [create xml document here]; declared outside the block of code and data: having a value of xmlDocument */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request - useless with Basic Authentication on Windows IIS7 */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request - useless with Basic Authentication on Windows IIS7 */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
			,beforeSend: function(me) {
			me.setRequestHeader('Authorization ', basicAuthData);				/* Basic Authentication method required for Windows IIS7 */
						  }
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    /* Go through the root node */
				    $(data).find(haveRootNodeTag).each(function() {
										   haveExpectedFormat = 1;
										   /* Iterate through each child node */
										   $(this).find(haveChildNodeTag).each(function() {
																   /* Grab the element name and description */
																   haveExpectedResponse = 1;
																   alert("Title = " + $(this).find("Title").text() + "\nDescription = " + $(this).find("Description").text());
																  } /* End Function */
														       ); /* End Each */
										   } /* End Function */
								    ); /* End Each */
				   } /* End Function */
		   )
	      .fail(
		    function(data) {
				    $('#userMsg').text("Loading XML data response failed with >> " + data.statusText + ".");
				   }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received an XML response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("XML was returned but not in the expected format.");
												     }
								     else { $('#userMsg').text("Loading XML data response completed."); }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     }
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

}); /* End document.ready */

</script>
</head>
<body>
Authenticate to a location on a website, then send XML and get a response.  <input type="button" value="Click Here" id="trigger" /> <div id="userMsg" />
</body>
</html>

XML USED

<?xml version="1.0" encoding="utf-8" ?>
<Info>
	<Item>
		<Title>Great Item</Title>
		<Description>A great item that should be added.</Description>
	</Item>
</Info>


READ SOAP-XML AND SEND SOAP-XML WITH ASMX WEB SERVICE [Download Zip Example]
JAVASCRIPT CODE

<html>
<head>
<script src="jquery-1.9.1.js" language="text/javascript" type="text/javascript"></script>
<script language="text/javascript" type="text/javascript">

// Wrap everyting in this READY directive
$(document).ready(function () {

	//alert( 'You are running jQuery version: ' + $.fn.jquery );
	var soapNetRequest = "", soapNetResponse = "";

	// When the button is clicked get SOAP-XML ENVELOPES to use (would be easier to already know what they are and skip this step)
	$('#soapPullEnvelope').click(function() {
		$('#userMsg').text("Getting SOAP-XML envelopes..."); // update status of AJAX call

		/* Define AJAX Settings for retreiving SOAP/XML for a single method (ie, function called in the ASMX code) */
		var ajaxURL = "./XML-Web-Service/XML-Web-Service/Service1.asmx";
		var ajaxType = "GET";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "html";
		var ajaxContentType = "application/x-www-form-urlencoded; charset=UTF-8";
		var ajaxAsynchronous = true;
		var ajaxCache = false;
		var ajaxCrossDomain = false;
		var ajaxDataToTarget = "HelloWorld";			/* Method in web service to get SOAP-XML envelopes for */
		var ajaxUseGlobalHandlers = false;
		var ajaxUsername = "";
		var ajaxPassword = "";
		var ajaxTimeout = 5000;

		var haveRootNodeTag = "SimpleWebSvc";
		var haveChildNodeTag = "incomingData";

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text html": true}						/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
		        ,data: ({op: ajaxDataToTarget})							/* Data to send to the target which is appended to the URL for GET requests as name/value pairs like { name: "John", location: "Boston" } or XML like var xmlDocument = [create xml document here]; declared outside the block of code and data: having a value of xmlDocument */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    /* Extract SOAP-XML Envelopes Specific to ASMX; the easiest way is to already know what they are (from documentation) or invoking the web service in a web browser. */
				    // alert(data); /* Simple way to determine what is being returned by the asmx file on the server */

				    /* Go through the returned html */
				    if (data.indexOf(haveRootNodeTag) > 0) {
									    haveExpectedFormat = 1;
									    if (data.indexOf(haveExpectedResponse) > 0) {
															 haveExpectedResponse = 1;
														        }
									   }
				    if (haveExpectedResponse === 1) {
								     /* Extract SOAP 1.2 */
								     var preliminaryData = data.replace(/\r\n/g, '').replace(/\r/g, '').replace(/\n/g, '').split("<h3>SOAP 1.2</h3>")[1].split("</span>")[0];
								     var soapRawRequest = preliminaryData.split("<pre>")[1].split("</pre>")[0];
								     var soapRawResponse = preliminaryData.split("</pre>")[1].split("<pre>")[1].split("</pre>")[0];
								     soapNetRequest = soapRawRequest.split(/\?xml version=\"1.0\" encoding=\"utf-8\"/)[1].replace(/\?&gt;/, "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;");
								     soapNetResponse = soapRawResponse.split(/\?xml version=\"1.0\" encoding=\"utf-8\"/)[1].replace(/\?&gt;/, "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;");
								    }
				   } /* End Function */
		   )
	      .fail(
		    function(data) {
				    $('#userMsg').text("Loading SOAP-XML data response failed with >> " + data.statusText + ".");
				   }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received a SOAP-XML response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("SOAP-XML was returned but not in the expected format.");
												     }
								     else {
									   $('#userMsg').html("Loading SOAP-XML Envelopes complete as: [REQUEST] " + soapNetRequest + " [RESPONSE] " + soapNetResponse);
									  }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     }
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

	// When the button is clicked perform the SOAP-XML send request to the web service on the server
	$('#soapSendMessage').click(function() {
		$('#userMsg').text("Sending SOAP-XML data..."); // update status of AJAX call
		/* Define AJAX Settings */
		var ajaxURL = "./XML-Web-Service/XML-Web-Service/Service1.asmx";
		var ajaxType = "POST";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "xml";
		var ajaxContentType = "application/soap+xml; charset=UTF-8";
		var ajaxAsynchronous = true;
		var ajaxCache = false;
		var ajaxCrossDomain = false;
		var ajaxDataToTarget = "";

		/* Grab the SOAP-XML Request Envelope to send to the web service on the server and filter <, > */
		ajaxDataToTarget = soapNetRequest.replace(/\&lt;/g, "<").replace(/\&gt;/g, ">");

		/* Insert value into the SOAP-XML Envelope we'll be sending to the web service on the server */
		ajaxDataToTarget = ajaxDataToTarget.replace("<font class=value>string</font>", "0123456789");

		/* Show the SOAP-XML that will be sent */
		$('#userMsg').text("Preparing to send the following SOAP-XML Request to the server as: " + ajaxDataToTarget);
		alert("-- Getting ready to send the SOAP-XML request as noted in page --");

		var ajaxUseGlobalHandlers = false;
		var ajaxUsername = "";
		var ajaxPassword = "";
		var ajaxTimeout = 5000;

		/* Handle SOAP-XML Response From Server */
		var haveRootNodeTag = "HelloWorldResult";
		var haveChildNodeTag = "inputData";

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text xml": jQuery.parseXML}					/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
		        ,data: ajaxDataToTarget								/* Data to send to the target which is appended to the URL for GET requests as name/value pairs like { name: "John", location: "Boston" } or XML like var xmlDocument = [create xml document here]; declared outside the block of code and data: having a value of xmlDocument */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    /* Locate "root" node */
				    if ($(data).find(haveRootNodeTag)) {
									haveExpectedFormat = 1;
									/* Locate child node */
									if ($(this).find(haveChildNodeTag)) {
													     haveExpectedResponse = 1;
													    }
								       }
				    /* Appears valid, get response value */
				    if (haveExpectedFormat === 1 && haveExpectedResponse === 1) {
											         alert("inputData = " + $(data).find(haveChildNodeTag).text());
												}
				   } /* End Function */
		   )
	      .fail(
		    function(data) {
				    $('#userMsg').text("Loading SOAP-XML data response failed with >> " + data.statusText + ".");
				   }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received a SOAP-XML response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("SOAP-XML was returned but not in the expected format.");
												     }
								     else { $('#userMsg').text("Loading SOAP-XML data response completed."); }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     }
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

}); /* End document.ready */

</script>
</head>
<body>
Working with SOAP-XML - broken down into individual steps detailed below:<br /><br />
<b>Step 1:</b> Get a web service's soap-xml operation schema / definition for a method that the service contains.  
This is just the "envelope" or "layout" that the web service expects to receive data as when you are ready to send data to it.  <input type="button" value="Get Envelope" id="soapPullEnvelope" />
<br /><br />
<b>Step 2:</b> Send data to a web service, usually referred to as sending the soap message, using the "envelope" you had received from step 1.  <input type="button" value="Send Message" id="soapSendMessage" />
<br /><br />
Status: <div id="userMsg" />
<br /><hr />
<b>NOTES:</b> As you can see, the SOAP 1.2/XML interface for the ASMX web service contains two envelopes; one for the request (which is what you send the server) and the response (what the server responds with).  
While this example grabs the html output of the "op" request in order to get the SOAP 1.2 "layout", normally you would already know in advance what the request and response "layout" are - meaning Step 1 would
not be necessary.  For some clarification as to what is being returned and parsed from Step 1 (in the event you cannot run the web service) the "layout" is included below:
<br /><br />
<b>SOAP-XML Request Envelope:</b><br />
<span style="color: blue;">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"&gt;
  &lt;soap12:Body&gt;
    &lt;HelloWorld xmlns="SimpleWebSvc"&gt;
      &lt;incomingData&gt;&lt;font class=value&gt;string&lt;/font&gt;&lt;/incomingData&gt;
    &lt;/HelloWorld&gt;
  &lt;/soap12:Body&gt;
&lt;/soap12:Envelope&gt;
</span>
<br /><br />
<b>SOAP-XML Response Envelope:</b><br />
<span style="color: blue;">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"&gt;
  &lt;soap12:Body&gt;
    &lt;HelloWorldResponse xmlns="SimpleWebSvc"&gt;
      &lt;HelloWorldResult&gt;
        &lt;inputData&gt;&lt;font class=value&gt;string&lt;/font&gt;&lt;/inputData&gt;
      &lt;/HelloWorldResult&gt;
    &lt;/HelloWorldResponse&gt;
  &lt;/soap12:Body&gt;
&lt;/soap12:Envelope&gt;
</span>
</body>
</html>

SOAP-XML USED

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <HelloWorld xmlns="SimpleWebSvc">
      <incomingData><font class=value>string</font></incomingData>
    </HelloWorld>
  </soap12:Body>
</soap12:Envelope>
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <HelloWorldResponse xmlns="SimpleWebSvc">
      <HelloWorldResult>
        <inputData><font class=value>string</font></inputData>
      </HelloWorldResult>
    </HelloWorldResponse>
  </soap12:Body>
</soap12:Envelope>


READ JSON [Download Zip Example]
JAVASCRIPT CODE

<html>
<head>
<script src="jquery-1.9.1.js" language="text/javascript" type="text/javascript"></script>
<script language="text/javascript" type="text/javascript">

// Wrap everyting in this READY directive
$(document).ready(function () {

	//alert( 'You are running jQuery version: ' + $.fn.jquery );

	// When the button is clicked perform the AJAX request
	$('#trigger').click(function() {
		$('#userMsg').text("Loading JSON data..."); // update status of AJAX call

		/* Define AJAX Settings */
		var ajaxURL = "data.json";
		var ajaxType = "GET";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "json";
		var ajaxContentType = "application/j-son; charset=utf-8";
		var ajaxAsynchronous = true;
		var ajaxCache = false;
		var ajaxCrossDomain = false;
		var ajaxDataToTarget = "";

		var ajaxUseGlobalHandlers = false;
		var ajaxUsername = "";
		var ajaxPassword = "";
		var ajaxTimeout = 5000;

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text json": jQuery.parseJSON}					/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    /* Go through each book */
				    $(data.Collection.Book).each(function(i, val) {
										   haveExpectedFormat = 1;
										   var bookTitle = "", bookRenderAs = "", bookPublisher = "";
										   /* Get publisher information on each book */
										   bookPublisher = val.Publisher;
										   /* Get book title name '#text' and attribute '-RenderAs' */
										   $.each(val, function() {
													   $.each(this, function(key, value) {
																	      if (/[^0-9]/.test(key) === true) {
																						/* Non-numeric key found; save it */
																						haveExpectedResponse = 1;
																						if (key === "#text") { bookTitle = value; }
																						if (key === "-RenderAs") { bookRenderAs = value; }
																					       }
																	     } /* End Function */
														 ); /* End Each */
													  } /* End Function */
											 ); /* End Each */
										   /* Output */
										   alert("bookpublisher = " + bookPublisher + "\nbooktitle = " + bookTitle + "\nbookrenderas = " + bookRenderAs);
										  } /* End Function */
								); /* End Each */
				   } /* End Function */
		   )
	      .fail(
		    function(data) {
				    $('#userMsg').text("Loading JSON data response failed with >> " + data.statusText + ".");
				   }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received an JSON response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("JSON was returned but not in the expected format.");
												     }
								     else { $('#userMsg').text("Loading JSON data response completed."); }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     } /* End Function */
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

}); /* End document.ready */

</script>
</head>
<body>
Get some JSON data from an external source.  <input type="button" value="Click Here" id="trigger" /> <div id="userMsg" />
</body>
</html>

JSON USED

{
  "Collection": {
    "Book": [
      {
        "Title": {
          "-RenderAs": "html",
          "#text": "Book number 1"
        },
        "Publisher": "Pub1"
      },
      {
        "Title": {
          "-RenderAs": "ascii",
          "#text": "Book number 2"
        },
        "Publisher": "Pub2"
      },
      {
        "Title": {
          "-RenderAs": "email",
          "#text": "Book number 3"
        },
        "Publisher": "Pub3"
      },
      {
        "Title": {
          "-RenderAs": "text",
          "#text": "Book number 4"
        },
        "Publisher": "Pub4"
      }
    ]
}}


SEND JSON WITH POST [Download Zip Example]
JAVASCRIPT CODE

<html>
<head>
<script src="jquery-1.9.1.js" language="text/javascript" type="text/javascript"></script>
<script language="text/javascript" type="text/javascript">

// Wrap everyting in this READY directive
$(document).ready(function () {

	//alert( 'You are running jQuery version: ' + $.fn.jquery );

	// When the button is clicked perform the AJAX request
	$('#trigger').click(function() {
		$('#userMsg').text("Sending JSON data..."); // update status of AJAX call

		/* Define AJAX Settings */
		var ajaxURL = "server-processing.aspx";
		var ajaxType = "POST";
		var ajaxAcceptedResponseFormat = "text/xml";
		var ajaxAcceptedResponseTxt = "text/plain";
		var ajaxResponseParseMethod = "json";

		var ajaxContentType = "application/x-www-form-urlencoded; charset=utf-8"; /* When JSON is being sent as a POST, this should be "application/x-www-form-urlencoded; charset=utf-8" (normally "application/j-son; charset=utf-8" is suggested for JSON).  With GET, it does not matter what this is set to. */
		var ajaxAsynchronous = true;
		var ajaxCache = false;
		var ajaxCrossDomain = false;

		/* While this uses an array, if you have contents of a form to send as json you could reference the form */
		var saveBook = new Object();
		saveBook.Title = "Book number 1";
		saveBook.RenderAs = "html";
		saveBook.Publisher = "Pub1";

		var ajaxDataToTarget = JSON.stringify(saveBook); /* Transforms the object into: {"Title":"Book number 1","RenderAs":"html","Publisher":"Pub1"} */
		ajaxDataToTarget = encodeURIComponent(ajaxDataToTarget); /* Transforms string to %7B%22Title%22%3A%22Book%20number%201%22%2C%22RenderAs%22%3A%22html%22%2C%22Publisher%22%3A%22Pub1%22%7D */

		var ajaxUseGlobalHandlers = false;
		var ajaxUsername = "";
		var ajaxPassword = "";
		var ajaxTimeout = 5000;

		var haveExpectedFormat = 0;
		var haveExpectedResponse = 0;
		var haveNonExpected = "";
		var haveRawResponse = 0;
		var haveRawResponseData = "";

		/* Begin AJAX Work */
		$.ajax({
		        accepts: {xml: ajaxAcceptedResponseFormat, text: ajaxAcceptedResponseTxt}	/* Accepted response data from the target */
		        ,global: false									/* Do not use global callback functions */
		        ,type: ajaxType									/* HEAD/GET/POST/DELETE */
		        ,contentType: ajaxContentType							/* Default content type */
		        ,url: ajaxURL									/* Target URL */
		        ,async: ajaxAsynchronous							/* if false, may lock browser until response is received */
		        ,cache: ajaxCache								/* true - will cache URL data returned; false - will not cache URL data but only for HEAD AND GET requests */
		        ,converters: {"text json": jQuery.parseJSON}					/* Formats response - {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} */
		        ,crossDomain: ajaxCrossDomain							/* Setting to true allows cross domain requests on the same domain and server-side redirection to another domain */
			,data: ({datasnd: ajaxDataToTarget})						/* Data to send to the target which is appended to the URL for GET requests as name/value pairs like { name: "John", location: "Boston" } or XML like var xmlDocument = [create xml document here]; declared outside the block of code and data: having a value of xmlDocument */
		        ,dataType: ajaxResponseParseMethod						/* "xml": Returns a XML document that can be processed via jQuery, "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM, "script": Evaluates the response as JavaScript and returns it as plain text, "json": Evaluates the response as JSON and returns a JavaScript object, "jsonp": Loads in a JSON block using JSONP, "text": A plain text string */
		        ,global: ajaxUseGlobalHandlers							/* true - allows global ajax event handlers to be used for request, false - no...we are handling it in the .ajax below */
		        ,ifModified: false								/* true - allow request success if response has changed since last request, false - ignore */
		        ,username: ajaxUsername								/* username to be used in response to a http authentication request */
		        ,password: ajaxPassword								/* password to be used in response to a http authentication request */
		        ,timeout: ajaxTimeout								/* Number of milliseconds to wait for a response from the target */
	      	      })
	      .done(
		    /* Parse the data response */
		    function(data) {
				    var bookTitle = "", bookRenderAs = "", bookPublisher = "";
				    bookTitle = data.Title;
				    bookRenderAs = data.RenderAs;
				    bookPublisher = data.Publisher;
				    haveExpectedFormat = 1; 
				    haveExpectedResponse = 1;
				    alert("Title = " + bookTitle + "\nRenderAs = " + bookRenderAs + "\nPublisher = " + bookPublisher);
//				    /* This is longer but steps through the returned JSON */
//				    $(data).each(function(i, val) {
//								   $.each(val, function(name, value) {
//												      alert("name = " + name + "\nvalue = " + value);
//												     } /* End Function */
//									 ) /* End Each */
//								  } /* End Function */
//
//						) /* End Each */
				   } /* End Function */
		   )
	      .fail(
		    function(data) {
				    $('#userMsg').text("Loading JSON data response failed with >> " + data.statusText + ".");
				   }
		   )
	      .always(
		      function(data) {
				      /* Check to ensure that we received an JSON response and with the expected elements */
				      if (haveExpectedFormat === 1) {
								     if (haveExpectedResponse === 0) {
												      $('#userMsg').text("JSON was returned but not in the expected format.");
												     }
								     else { $('#userMsg').text("Loading JSON data response completed."); }
								    }
				      else {
					    /* More checking for non-expected response such as server error/message page */
					    haveRawResponseData = data.responseText.toLowerCase();
					    if (haveRawResponseData.indexOf("<title") !== -1) {
												haveNonExpected = haveRawResponseData.split("<title>")[1].split("</title>")[0];
											      }
					    /* Inform the user and grab the raw response with any accompanying tags and markup */
					    if (haveNonExpected.length === 0) { haveNonExpected = "An unknown data response was received >> " + haveRawResponseData; }
					    else { haveNonExpected = "A data response of \"" + haveNonExpected + "\" was received >> " + haveRawResponseData; }
					    $('#userMsg').text(haveNonExpected);
					   }
				     } /* End Function */
		     )
		; /* End AJAX Work */

	}); /* End Button Click */

}); /* End document.ready */

</script>
</head>
<body>
Send some JSON data to an external source.  <input type="button" value="Click Here" id="trigger" /> <div id="userMsg" />
</body>
</html>

JSON USED

{
	"Title":"Book number 1",
	"RenderAs":"html",
	"Publisher":"Pub1"
}


XML and JSON Markup
One very useful utility that I've found for observing the structure of XML and JSON is using the XML/JSON converter.

About Joe