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();
}

6 comments:

ninest123 said...

replica watches, louis vuitton, air jordan pas cher, longchamp pas cher, ray ban sunglasses, nike air max, oakley sunglasses, ugg boots, oakley sunglasses, nike free, nike roshe run, louboutin shoes, michael kors, louboutin, longchamp outlet, louis vuitton outlet, polo ralph lauren outlet, longchamp outlet, tiffany jewelry, tiffany and co, jordan shoes, tory burch outlet, ugg boots, air max, louis vuitton, replica watches, nike free, louis vuitton, uggs on sale, sac longchamp, burberry, chanel handbags, oakley sunglasses, polo ralph lauren outlet, louboutin outlet, longchamp, louis vuitton outlet, prada outlet, cheap oakley sunglasses, oakley sunglasses, christian louboutin outlet, louboutin pas cher, ralph lauren pas cher, ray ban sunglasses, kate spade outlet, ray ban sunglasses, nike air max, prada handbags, gucci outlet, nike outlet

ninest123 said...

burberry outlet online, nike air max, coach purses, nike air max, michael kors, timberland, new balance pas cher, true religion jeans, kate spade handbags, nike free run uk, north face, true religion jeans, ralph lauren uk, air force, hollister pas cher, ray ban uk, converse pas cher, lacoste pas cher, michael kors outlet, michael kors outlet, ugg boots, michael kors outlet, michael kors outlet, coach outlet, vans pas cher, hollister, burberry, coach outlet, nike blazer, oakley pas cher, vanessa bruno, mulberry, ugg boots, lululemon, hermes, tn pas cher, ray ban pas cher, sac guess, hogan, true religion jeans, abercrombie and fitch, true religion outlet, michael kors, nike air max, michael kors outlet, replica handbags, michael kors, nike roshe, north face, michael kors

ninest123 said...

burberry outlet online, nike air max, coach purses, nike air max, michael kors, timberland, new balance pas cher, true religion jeans, kate spade handbags, nike free run uk, north face, true religion jeans, ralph lauren uk, air force, hollister pas cher, ray ban uk, converse pas cher, lacoste pas cher, michael kors outlet, michael kors outlet, ugg boots, michael kors outlet, michael kors outlet, coach outlet, vans pas cher, hollister, burberry, coach outlet, nike blazer, oakley pas cher, vanessa bruno, mulberry, ugg boots, lululemon, hermes, tn pas cher, ray ban pas cher, sac guess, hogan, true religion jeans, abercrombie and fitch, true religion outlet, michael kors, nike air max, michael kors outlet, replica handbags, michael kors, nike roshe, north face, michael kors

ninest123 said...

longchamp, iphone 5s cases, hollister, ferragamo shoes, herve leger, jimmy choo shoes, giuseppe zanotti, north face outlet, vans shoes, mont blanc, nike huarache, celine handbags, iphone cases, iphone 6s cases, nike trainers, lululemon, louboutin, ralph lauren, iphone 6 cases, babyliss, s5 cases, hollister, north face outlet, nfl jerseys, bottega veneta, soccer shoes, oakley, baseball bats, abercrombie and fitch, ghd, chi flat iron, valentino shoes, beats by dre, asics running shoes, wedding dresses, reebok shoes, timberland boots, ipad cases, mac cosmetics, mcm handbags, nike roshe, nike air max, insanity workout, iphone 6s plus cases, birkin bag, p90x workout, hollister, instyler, iphone 6 plus cases, soccer jerseys, new balance

ninest123 said...

barbour jackets, toms shoes, lancel, supra shoes, juicy couture outlet, moncler, moncler, louis vuitton, thomas sabo, hollister, canada goose uk, canada goose, louis vuitton, doudoune canada goose, converse outlet, canada goose outlet, replica watches, bottes ugg, canada goose outlet, nike air max, gucci, moncler, pandora jewelry, canada goose, karen millen, marc jacobs, converse, moncler, ray ban, wedding dresses, montre pas cher, ugg,ugg australia,ugg italia, moncler, pandora charms, canada goose, moncler, canada goose, ugg,uggs,uggs canada, moncler, vans, swarovski crystal, sac louis vuitton pas cher, pandora jewelry, juicy couture outlet, louis vuitton, louis vuitton, moncler outlet, coach outlet, swarovski, ugg boots uk, links of london, ugg pas cher, pandora charms

chenmeinv0 said...

hollister clothing
coach outlet store online
cheap rolex watches
tiffany and co jewelry
cheap ray ban sunglasses
replica rolex watches
coach outlet store online
true religion
prada handbags
discount ray ban sunglasses
2016.12.17xukaimin