Tuesday 13 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Calling a Web Service with AJAX

There are different ways to call a web service in JavaScript, but the best ones are done with AJAX. I have decided to add the same call but with different formats, so you can’t get lost and choose your favourite.

url: Web service address
type: Protocol, you can choose between GET and POST
timeout: Who long it is your application waiting for the web service.
dataType: Type of data, it could be text , json etc.
contentType: The content type you want, ie: "application/json; charset=utf-8",
cache: Read example below…
datafilter: Read example below…
Accepts:
Read example below…

METHOD 1

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text'
     }).done(function (responsetext) {
         //do something
     }).fail(function () {
         //do something
     });



METHOD 2

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text',
         success: function (responsetext) {
             //do something
         },
         error: function (e) {
             //do something
         }
     });




If you don’t specify an error handling jQuery will keep running.



To work with JSON so you can pass data across, JavaScript provides JSON.stringify and JSON.parse.



If you want to send JSON data , you can use something like this (Thanks Bobby):

 function InfoByDate(sDate, eDate) {
        var divToBeWorkedOn = "#AjaxPlaceHolder";
        var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
        var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $(divToBeWorkedOn).html(msg.d);
            },
            error: function (e) {
                $(divToBeWorkedOn).html("Unavailable");
            }
        });
    }



The onreadystatechange event is key in AJAX. This is the only way to monitor what is going on. We have three core properties. Please check the values and the example.



onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes

readyState
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status
200: "OK"
404: Page not found

<html>
<head>
<script>
    function loadXMLDoc() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "ajax_info.txt", true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I recently show this question in a what it could be a Microsoft exam, and I think it will be quite useful to try to understand ajax calls, it is based on the accepts and datafilter parameter:

You are developing a web application that retrieves data from a web service. The data being retrieved is a custom binary datatype named bint. The data can also be represented in XML. Two existing methods named parseXml() and parseBint() are defined on the page. The application must:
· Retrieve and parse data from the web service by using binary format if possible
· Retrieve and parse the data from the web service by using XML when binary format is not possible



You need to develop the application to meet the requirements. What should you do? (To answer, drag the appropriate code segment to the correct location. Each code segment may be used once, more than once, or not at all. You may need to drag the split bar between panes or scroll to view content.)

          var request = $.ajax({
            uri:'/',
            accepts: 'application/bint, text/xml',
            datafilter: function(data,type){
                if(request.getResponseHeader("Content-Type")=="application/bint")
                   return parseBint(data);
                else
                   return parseXml();
                 },            
            success: function (data) {
              start(data);
            }
        });


Another interesting example is the way you can display on-line stock rates in real time. One of the features we should use to get a time stamp in the header is cache set to false. This will force requested pages not to be cached by the browser. I attach an example:

var stockRate;
function getResults(){
$.ajax({
            async: false,
            cache:false,
            type: "POST",
            url: "stockrates.asmx/rates"
            data: {'stockname':stockName},
            dataType: "json",
            success: function (msg) {
               stockRate=result;
        });
        ShowRate();
}