Ajax to XML Web Service

Recently I have been doing some browser/client side work, using HTML5, CSS3 and JavaScript, integrating with a Learning Management Solution (LMS) and a separate Assessment application.

Much of the work has been confined to using existing LMS function and working within the confines of a DIV provided by the LMS.

I am gradually exposing the assessment application functionality through direct URLs and iFrames and am not starting to pull data down via web services to enable tighter integration.

This brings us back to the title of this post, I need to use JavaScript and AJAX to work with the web services to update the data on the page without leaving the html page. AJAX calls are by their nature asynchronous, we call them and don’t know how long it will take to return anything so callback functions are required to do anything meaningful with the data when it is returned.

The below fragment is a sample of how this is done. For my case, everything is done over https, so any data sent is encrypted.

// this is the entry point, called from an onClick action from a DIV in the HTML
function CallWebServiceAndDoSomething() {
DoCallWebService(CallWebServiceAndDoSomethingPartTwo);
}

// this is the main function to look at, the $.ajax() call is the bit that does the work
function DoCallWebService(callbackFunctionName) {
var userID = GetUserId();
// Here is the AJAX call to the web service, there are lots of optional parameters so this just shows the ones I use
$.ajax( {
type: “POST”,
contentType: “application/x-www-form-urlencoded”,
url: WS_URL,
data: {Key: USER_KEY, UserID: _userId},
success: function (xmlData) {
// we just want the value in the first XML child node
var node, childNodes = xmlData.documentElement.childNodes;
var innerXml = childNodes[0];
var myValue = JSON.parse(childNodes[0].nodeValue);
callbackFunctionName(myValue);
},
error: function (err) {
// if an error occurs, I write something out to the console
console.log(“AJAX error in request: ” + JSON.stringify(err, null, 2));
}
});
}

// here we get called on successful completion of the AJAX call to the web service
function CallWebServiceAndDoSomethingPartTwo(encryptionString) {
// create iFrame element
var iFrameHtml = ‘<iframe width=”820″ height=”450″ src=”/assess.php?uid=’ + encryptionString + ‘”></iframe>’;
document.getElementById(“MyAssesmentIFrame”).innerHTML = iFrameHtml;
// display new page/div
ShowPageAction(‘MyNewPage’);
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *