i am not getting what exactly happens when we use ajax.Page doesn't get refreshed everytime means what? is it related to page_load method or what
Your explorer makes a nem connection to server and retrieve data. Or if connection is keeped alive it uses alive one.
The browser does http calls on a background thread, and you use javascript to modify the DOM when the result returns. This prevents you from refreshing the whole page and can modify parts on it at will.
Check out the definition at wikipedia for more information.
If you do ajax in a asp.net application page_load will be called for the page you request, just like a normal call. It's the rendering in the browser which is different. ¨ Key concepts: background calls and scripting.
Using JavaScript, it is possible to make calls to webpages. Also, using JavaScript, it is possible to replace the content of the page with something new (by manipulating the DOM).
So, Ajax (Asynchronous JavaScript) is the process of combining these two techniques. You visit some page (typically one on your own server), get the results of it, and then take that data, and do something with it (change the page in some fashion).
This is the core idea.
Ajax is a simple Javascript code. and the page isn't been refreshed by itself, you need to refresh it - when you think it's necessary ( we usually based it on you server's result after the request came back ).
Yes, it opens a background connection from your browser to your ASP page. and when you'r done - you can update only one DOM object in your page.
What it's for ? why do we use it ? look at facebook for example, when you dismiss a notification, ignoring, approving, comment on your what your friend has in mind - you don't refresh the page - you ( as a developer ) can change the client's properties ( in the DB for ex) with/out letting him know.
plus, you can do all the above with just refreshing the page ( which is very annoying to the client ) , and you always have to warry about all the args that needs to be passed to each new document.
The ajax way can let you make one action, without moving to anywhere. it's very comfortable as a developer to use it, and the client enjoy it more.
and there are JS frameworks that makes it really simple. for example: ( this example is a jQuery example .. )
function call_my_page() {
$.post("/get_list.asp", {
param1: "a",
param2: "b"
}, function ( server_response ) {
alert(server_response);
if ( server_response == 1 ) { window.location.refresh; }
}
}
call_my_page();
the get_list.php - this is the file on your server which will be posted ( $.post )
param1, param2 - it's vars you pass to your server.
and if you server's page file returns the answer "1" then - your page will be refreshed. ( or only a DIV / SPAN / TABLE will be replaced with a new HTML )
jQuery. is the best.
Go to any SO post with more than a couple of comments and you will see a link that says something like show 99 more comments below that. Now if you click on it, you can see that the said 99 comments are loaded in a second or two, while the remaining page stays undisturbed. This is because the 'page doesn't get refreshed' - it would have taken longer had the page been refreshed as it would mean reloading the whole html content.
Instead of resending the whole html page (including other posts in the same thread), server sends only the requested data (just those 99 comments in our example).
The possibilities are enormous. Server can return any data - html or text or xml or json or whatever. You can display the received data using javascript.
The server side code handles an AJAX request the same way it handles a normal http request (you can override this using HTTP_X_REQUESTED_WITH
header though).
To explain AJAX you have to understand the non AJAX way and see the difference so I will give the same example in the traditional form post way and the AJAX way.
The scenario you have a list of phone numbers you want to be able to add any number of phone numbers for a client, each record has two fields, type and number. Type is a description e.g. Mobile Home Work.
The Traditional
The user see a list of phone numbers with the last one being empty and editable. They want to add one more phone number so they fill in the empty fields and click the add button. The form is submitted, so the data is wrapped up in an http post and sent to the server, the server code adds the phone record to the database and starts to construct the html for the new page so it starts with the htm, head, all the script includes, and then the table with the data in including the new row with the new phone number and another empty field.
Request
POST /addPhoneNumberForm Http 1.1
HOST:www.host.com
USER-AGENT:...
...
newPhoneType=Home&newPhoneNumber=00649123456
Response
<DOCTYPE ....>
<html>
<head>
<title="...">
<link type="text/css" href="standard.css" />
<script type="text/javascript" src="jQuery1.4.js"></script>
...
</head>
<body>
<div id="headerAndNav">
....
</div>
<div id="content">
....
<table id="addPhoneRecords" class="dataentry">
<tr><th>Description</th><th>Number</th></tr>
<tr><td>Mobile</td><td>0044987654331</td></tr>
<tr><td>Work</td><td>0044987654332</td></tr>
<tr><td>Holiday</td><td>0044987654333</td></tr>
<!-- Newly Added -->
<tr><td>Home</td><td>00649123456</td></tr>
<tr><td><input type=text .../></td><td><input type=text .../></td></tr>
</table>
....
</div>
<div id="footer">
...
</div>
</body>
</html>
Once the users browser receives this response it throws away all the user can see replaces this with a white, blank screen. And start parsing the html received as a completely new page. Any Images/Css/Javascript files have to be re-fetched (or at least check if the cache is valid). Any javascript files have to be run and all the accompanying DOM events need to file (document.onLoad etc).
So what has happened is the user has submitted data and the server has replied with a completely new page. There has been a cost of doing this of a lot of network activity and time and cpu cycles on both the server and the client as they have had to generate, and parse a complete html page.
The AJAX Way
The user see a list of phone numbers with the last one being empty and editable. They want to add one more phone number so they fill in the empty fields and click the add button. That bit was the same as the traditional, from now on in it gets different. When the user clicks the button instead of the form submitting a peice of javascript collects up the relavent information from the form and make an AJAX request to the server using a XMLHttpRequest, this sends a request similar to a form post but the result will be returned as a javascript string not as a web page.
Request
POST /addPhoneNumberAJAX Http 1.1
HOST:www.host.com
USER-AGENT:...
...
newPhoneType=Home&newPhoneNumber=00649123456&ajax=true&type=json
There are a large number of choices of what the server can return I have picked one example Response
{phoneType:"home",phoneNumber:"00649123456"};
This is in JavaScript Object Notation (JSON) and represents an object with two types phoneType and phoneNumber. Once this is received JavaScript is used to dynamical add a new row to the existing table. The javascript would look something like this.
addPhoneViaAjax(type, number, reqObj, xmlhttp){
// Construct url and declare parameters for our request
xmlhttp.open("POST","addPhoneNumberAJAX?newPhoneType="+type ...,false);
// Send the request and wait for the response
xmlhttp.send(null);
// For example assume response successful
// Get the response as text
var responseStr = xmlhttp.responseText;
// Convert the response to object, preferably using one of the JSON parsing libaries
var responseObj = eval(responseStr); // Please use one of the JSON parsing libaries look at Jquery.forms plugin
// Use jquery javascript libary to update the table in place.
// by finding the last row of the table and instering html before it.
jQuery("table#addPhoneRecords tr:last-child").before(
"<tr><td>" + responseObj.phoneType +
"</td><td>" + responseObj.phoneNumber +
"</td></tr>");
}
Summary So with traditional method the browser considers the response a whole new page and must do everything required to draw a new page. With the ajax approach the browser stays on the same page and you use javascript to alter one very small piece of the page.