Using JQuery Ajax functions to retrieve data from the server

In this post I would like to talk about the great support that JQuery has for Ajax.I have already written another post on my blog regarding the Jquery Ajax functions and how we can get data form the server.In that post we looked into how we can use the load() method to get data from the server.One of the things you must keep in mind is that JQuery is able to communicate with any server that uses standard protocols.In this post I would like to talk about the get(),post() and ajax() methods and how we can use those methods to get data back from the server through a web service that is hosted there.

The load() function provides us with a very easy way to get HTML data from the server into our application but sometimes we need to be more flexible.By flexible I mean to get JSON , XML data from the server.We can get this type of data from the server using the get() and post() methods.


1) Launch Visual Studio 2010. I am using the ultimate edition but the express edition will do just fine. Create an ASP.Net web application and choose C# as the development language.Give your application an appropriate name

2) We will show how to get html data from the server using the get() method as we did in my other post using the load() method. Add another item to your application, an html page. Name it LoadHtmlFromServerGet.html .  This is going to be a very simple page

<body>
<h1>Load HTML Content from the Server using JQuery</h1>
<br />
<button id="niceButton">
Click here to load HTML from the Server using the Get method!!!!
</button>
<div id="maindiv"></div>
 
 
</body>

 

3) Add another item to your project, an html page. I have named mine jqueryintro.htm.The html markup for my html page is following

 

<body>
<div>jQuery is a fast and concise JavaScript Library that 
simplifies HTML document traversing,event handling, animating,
and Ajax interactions for rapid web development. <strong>
jQuery is designed to change the way that you write JavaScript.</strong>
</div>
 
<div id="new">
 
 
<p><h3>Download jQuery</h3>
 
This is the recommended version of jQuery to use for your application. The code in
here should be stable and usable in all modern browsers. </p>
</div>
 
</body> 

4) I want to load the contents of the jqueryintro.htm in the "maindiv" ID, when the user clicks the button.I will do that by using the get() JQuery Ajax function.We will use this function to make a request to the server.

5) We have to add the following javascript/jquery code to the head section of the LoadHtmlFromServerGet.html

 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    
   <script type="text/javascript">
        $(document).ready(function () {
            $('#niceButton').click(function () {
                $.get('jqueryintro.htm'function (data) {
                    $('#maindiv').html(data);
                });
            });
        });
 </script>

This is very similar with the load() method.As you can see the get method does not operate on a wrapped set from a selector.It cannot directly update the matched set.

It uses a callback function to do that.

View the page on the browser and click the button to get the data from the server.

8) Now let's have a look on how you can access and get data from a web service.Add a new html page to your application,Loadfromwebservice.htm.

I will pass some parameters/data from this html page to a web service method and get results back.

The markup for this page

<body>
 
	<div id="livfootballers">
		
        <a href="#">kenny</a>
        <a href="#">steven</a>
	
	</div>
 
    <div id="results"></div>
 
</body>

 

 Add a folder in your project. Name it "thefootballers". Inside there i have place two .htm files. I have called the first one kenny.htm and the second one steven.htm.

 The content inside this pages is simple html

 kenny.htm

<body>
<p>
Kenneth Mathieson "Kenny" Dalglish.....
 
</p>
</body>
steven.htm 
 <body>
<p>
Steven Gerrard is.....
 
</p>
</body>
 

The web service method when invoked from the client will get the data from the .htm files and incorporate in the calling html page. 

9) Add a new item on your application , a web service. Name it AjaxJquery.asmx

 Make sure you uncomment this line of code.

   [System.Web.Script.Services.ScriptService]

 I am going to have to create a new method that takes some data from the client page and then sends back data from the relevant .htm page that resides on the server.

 The code for the method follows

        [WebMethod]
        public string FootBallerData()
        {
            string thefootballer = this.Context.Request["footballer"];
            if (thefootballer == ""return string.Empty;
 
 string file = Server.MapPath("~/thefootballers/" + thefootballer + ".htm");
            StreamReader sr = File.OpenText(file);
            string contents = sr.ReadToEnd();
            return contents;
        }

I am storing the data I got from the client side in a variable and then find the .htm file based on that parameter and finally I load the contents of that file in a variable.

10) Now we have to write some javascript code in our Loadfromwebservice.htm page.

I will use the get and post utility methods to send data to the appropriate service method. Inside the <head> section of the page,

I type the following:


    <script src="Scripts/jquery-1.5.js" type="text/javascript"></script>
    <script type="text/javascript">
        // get method
    $(function () {
      $('#livfootballers a').click(function (e) {
         $.get(
	'AjaxJquery.asmx/FootBallerData',
	{ footballer: $(this).text() },
 
	function (response) {
	$('#results').html($(response).text());
		}
	);
                return false;
            });
        });
 
        // post method
        $(function () {
            $('#livfootballers a').click(function (e) {
                $.post(
		'AjaxJquery.asmx/FootBallerData',
	'footballer=' + $(this).text(),
	function (response) {
	$('#results').html($(response).text());
		}
	);
                return false;
            });
        });
</script>

Both methods work equally well.you can comment out one if you want and just use the other one.

11) View the page on the browser and click the links. By doing that you pass the web service that is hosted on the server a parameter (kenny or steven).Then we take the response back from the service and by using the html() method we attach the returned html content to the div with ID results.

12) Let's see now how we can get different type of data from the server and not just html. We can get back JSON data and incorporate it to our html page.

Add a new item in your application , a class file. Name it Footballer.cs

public class Footballer
{
    public int ID { getset; }
    public string FirstName { getset; }
    public string LastName { getset; }
}

 Add a new item in your project , a web form. Name it Footballers.aspx.

The code inside the Footballers.aspx.cs file follows

 

public partial class Footballers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/json";
            var footballer = new Footballer
            {
                ID = int.Parse(Request["id"]),
                FirstName = "Kenny",
                LastName = "Dalglish"
            };
            var serial = new DataContractJsonSerializer(typeof(Footballer));
            serial.WriteObject(Response.OutputStream, footballer);
        }
    }

In the Page_Load event handling routine we construct in memory an object of type Footballer.Then I serialize the object to JSON data. For the folks that do not know what JSON is and why we use it to exchange data among systems have a look here.

Now we need to create another html page. We add a new page to our application and I will name it GetJSON.html

The markup for the page is very easy

 

<body>
 
<button id="JsonButton">Click here to get Json</button>
<div id="results"></div>
 
 
</body>

 Inside the <head> section of the GetJSON.html,  I will write the following javascript code. I am using the getJSON method.

 

    <script type="text/javascript">
    $(document).ready(function () {
      $('#JsonButton').click(function () {
          $.getJSON('Footballers.aspx', { id: 2 },
           function (data) {
              alert('ID: ' + data.ID + ' ' +
              data.FirstName + ' ' + data.LastName);
           });
       });
    });
    </script>

View the page in the browser and click the button. You will pass the ID (id =2) from the client to the server and back to the client. You have placed in the alert box a JSON object.

13) Now I would like to move one and create a simple example using the ajax() method.We can use this method if we want to have full control over making Ajax calls to the server.

Add another web form to your application, name it GetFootballteams.aspx

We will use the ajax() method to get the data from a web service and bring it back to the client.

 The markup follows

<head>
<title>Football Teams</title>
	
<script src="Scripts/jquery-1.5.js" type="text/javascript"></script>
<style type="text/css">
#result { displaynone; }
</style>
<script type="text/javascript">
$(function () {
$('#buttonTeam').click(function () {
    $.ajax({
	   type: "POST",
	   url: "FootballService.asmx/GetTeams",
	   data: "{}",
           contentType: "application/json; charset=utf-8",
	   dataType: "json",
	   success: function (response) {
	   $('#result').html('')
	.append('<p>Here are the teams:</p><ul id="teamsList">');
 
	var teams = response.d;
	for (var i = 0; i < teams.length; i++) {
	$('#teamsList').append('<li>'
		+ teams[i].Name + ' football club, resides on '
		+ teams[i].City + ' and was established on, '
		+ teams[i].Created
		+ '</li>');
	                    }
	                    $('#result').css('display''block');
	                }
	            });
	        });
	    });
 
	
	</script>
</head>
<body>
	<h1>Football Teams</h1>
	<button type="button" id="buttonTeam">Get Teams</button>
	<div id="result"></div>
</body>

Let me explain what I am doing here.I wire up the click even to the button.

$('#buttonTeam').click(function () { ....

Then I call the GetTeams method from the service.I am going to use a POST call to the server.The content that it sends back is JSON.

 Then I append some text to the div result.

success: function (response) {
	   $('#result').html('')
	.append('<p>Here are the teams:</p><ul id="teamsList">'); ..........

 

Then I loop through this set of teams by using the response.d property. Then I append each item and their respective properties in the teamList item I created above.

 var teams = response.d;
	for (var i = 0; i < teams.length; i++) {
	$('#teamsList').append('<li>'
	+ teams[i].Name + ' football club, resides on '
	+ teams[i].City + ' and was established on, '
	+ teams[i].Created
	+ '</li>');
	}

 I am sure you can see how much more power and flexibility we have with the ajax() method.

 

Now we must create the web service.

14) Add another item to your project, a web service. Name it FootballService.asmx

 Make sure you uncomment this line of code.

   [System.Web.Script.Services.ScriptService]

The code inside is

 public class FootballTeam
        {
     public string Name { getset; }
     public string City { getset; }
     public short Created { getset; }
        }
 
List<FootballTeam> FootballTeams = new List<FootballTeam>
{
new FootballTeam{Name = "Liverpool", City = "Liverpool", Created = 1892},
new FootballTeam{Name = "Everton", City = "Liverpool", Created = 1878},
new FootballTeam{Name = "Man Utd", City = "Manchester", Created = 1878},
new FootballTeam{Name = "Arsenal", City = "London", Created = 1886},
new FootballTeam{Name = "Tottenham", City = "London", Created = 1882}
};
 
        [WebMethod]
        public List<FootballTeam> GetTeams()
        {
            return FootballTeams;
        }
    }

 

It is very easy to understand what I am doing in the web service. I have a method GetTeams that return a generic .Net list object, FootballTeams to the client .Before that I create a FootballTeam class and then instantiate a list object FootballTeams.

View the page in the browser and click the button. You will get all the JSON data back from the service.

Have a look the the picture below and see the JSON objects returned in the response.

 

Well, I am sure you will agree with me when I say that noone has any doubts why Microsoft was so keen on incorporating/embracing the JQuery library into their products.

Microsoft favors JQuery over Ajax Javascript library because of its huge power

Hope it helps!!!!! Email me if you need the source code.

2 Comments

Comments have been disabled for this content.