Com And Hosting

In this example I have shown how to call a web-service using jQuery AJAX. For instance I wanted to load some addition information or external information in my website using web-service and Ajax call. If you do not know how to create a web-service then you open your website in Visual Web Developer 2005/2008/2010 right click on the root directory in file browsing (explorer) window and click on add new item. Select web-service from the suggested list and name it whatever you like. Usually it places the code file in APP_CODE folder. I have created a simple web-service called myService.asmx, here is my code –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for myService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class myService : System.Web.Services.WebService {

    public myService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string cityWeather(string city)
    {

        if (city=="Dhaka")
            return "City: " + city + "- Sunny. This is the time to go out and have fun. fsd";
        else
        return
            "City:" + city + "- Cloudy";

    }

}

The purpose of this web-service to display some information depending on user input in URL query string. Basically the URL will include a city name and web-service will display the weather information for that city. I have tried to make this simple to understand.

Once my web-service is ready, I have called the web service from aspx page using jQuery Ajax. First include the jquery script in the header section of your aspx page. If you don’t have jquery file then you can download it from jQuery website.

<head>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

</head>
<body>
<h2>AJAX call using jQuery in ASP.NET </h2>

</body>

To grab the query string parameter I had write a javascript function, you might do it in different way. I have used only java to accomplish this functionality.

        // Read a page's GET URL variables and return them as an associative array.
        function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

 

Here is the code of AJAX call in my aspx page –

var ct=getUrlVars()["name"] ;

        $.ajax({
            url: "services/myService.asmx/cityWeather",
            dataType: "html", // data type can have text
            type: "post",
            data: { city: ct },
            error: function (err) {
                alert("Error: " + err.toString());
            },
            success: function (data) {
                $("#cityWeather").html(data);
            },
            async: false,
            timeout: 2000

        });

 

In the jQuery ajax call, I am calling the cityWeather function from myService.asmx page using URL parameter name.

I also have a html div to display or load the content. Here is the div code –

<div id="cityWeather">

</div>

Well so far so good and working well. I thought it would be nice to display a loading image when content is loading. Depending on the length of the content and source of the content it might take a few seconds to load. To give better user experience here is what I have done, I have included a loading gif file while content loading.

 

<script type="text/javascript">

    $(document).ready(function () {

        // display temp image while loading the content
        $("#cityWeather").html("<img src='images/al1.gif' />");

      // get the query string value
        var ct=getUrlVars()["name"] ;

        $.ajax({
            url: "services/myService.asmx/cityWeather",
            dataType: "html", // data type can have text
            type: "post",
            data: { city: ct },
            error: function (err) {
                alert("Error: " + err.toString());
            },
            success: function (data) {
                $("#cityWeather").html(data);
            },
            async: false,
            timeout: 2000

        });

        // Read a page's GET URL variables and return them as an associative array.
        function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

    });
</script>

The sreen looks like this-

Web-service Call

 

 

Leave a Reply

Your email address will not be published.