Sending AJAX requests

Όνομα: *
Το email μου: *
Email παραλήπτη: *
Μήνυμα: *
Τα πεδία με έντονους χαρακτήρες είναι υποχρεωτικά.
Δεν έχετε συμπληρώσει όλα τα απαιτούμενα στοιχεία Το email που δώσατε δεν είναι σωστό

In a previous article we had some talk concerning AJAX. We used AJAX to read some simple file. Even though this may have seemed to be quite nice it is but a simple example of what AJAX can do. Things are going to get more interesting in this article where we will be talking about AJAX requests. In other words, how to exchange data between an html page and a server page depending on the requests parameters.
 

GET and POST

HTTP Request Methods, describe what the request is about to do. If this isn't the first time you are dealing with the web, you might have probably heard of the two most common methods, GET and POST.
 
Let's try to describe what these terms actually mean. To begin with, both requests contain information. For example whether we ask for the second page inside a forum or fill out and send a form in a contact page, we send information to the server. However you may be able to tell the difference between these requests. In the first example we are asking the server for data. In the second, it is us who send data to the server. If you understand that, you got the main difference between a GET and a POST request.
 
Since a GET request asks for data everyone can see, its variables are put in the url (query string).
http://dotnethints.com/news?id=16. This is a GET request that will return a news page having id 16. 
http://dotnethints.com/contact. This is a POST request that will submit the form, but a user will not be able to see its variables since they are not visible.
That way a POST request is more secure than a GET.
 
Based on the url, a GET request, in contrast to POST, can be cached, bookmarked or be used for every reason the url is all we need.
Since a GET request is used for requesting data, we do not expect to send much data, but in case you do find yourself sending more than a few KBs of data (actual limit depends on the browser you use), keep in mind that you have to use POST as GET will not support such an action.
 
So far, we've talked about HTTP Request Methods. Being part of the HTTP, they apply everywhere; ASP. NET, JAVA, PHP, everywhere. We are now going to see how to use what we've covered to create AJAX requests.
 

AJAX and GET

Here's a brief reminding of what we did last time. We used the following JavaScript function to get and handle an xml file.
 
function loadXML(url) {
            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 () {
                //Check if you are ready
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    //Code that handles the response                   
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
 
If you need to refresh your memory this is the article concerning AJAX introduction.
 
We are now going to create a simple search form using pure HTML, where the user will insert his search keyword, and a JavaScript function that will send it to the server asynchronous. The server will process the data and response (since we presume that our full-detailed database knows everything) that the search is successful.
 
Since we are using AJAX everything happens asynchronous. The page will not postback, the user will still see the same page and the server will not need to process the whole of the page.
 
So, here's the form
 
    <div>
        Keyword: <input type="text" id="KeywordInputID" />
        <button onclick="search()">Search</button>
        <br />
        <span id="ResponseSpanID" />
    </div>
 
It looks like this.
 
 
ajax Get form
 
 
 
The ResponseSpanID span will be used to show the message in the server response.
 
And here's the function
 
function search() {
            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("ResponseSpanID").innerHTML = xmlhttp.responseText;
                }
            }
            var url = "AjaxAdvanced.aspx?search=" + document.getElementById("KeywordInputID").value;
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
 
As you can see all we have to do is create the url we need
var url = "AjaxAdvanced.aspx?search=" + document.getElementById("KeywordInputID").value;
using the value form the input box. Remember, this is a GET request, so we use the url to send our data.
 
Keep in mind that sending data such as a search keyword using a GET request is not a bad good idea considering what we said earlier. We are asking the server for data, so we will use GET.
 
So far we have used HTML and JavaScript. This means we could request every page we wanted no matter what its platform is. However since this is a .Net site we will request the AjaxAdvanced.aspx page.
 
The page could contain much HTML and code processing but all we need for our little example is this.
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxAdvanced.aspx.cs" Inherits="Ajax_AjaxAdvanced" %>
 
and the code behind
 
using System;
 
public partial class Ajax_AjaxAdvanced : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //GET uses the query string
        if (Request.QueryString["search"] != null)
        {
            string search = Request.QueryString["search"].ToString();
 
            //Searching...
            //Supposing search had results
 
            Response.Write("Your search for " + search + " had the following results...");
        }
    }
}
 
I guess the code is quite simple. First we check if we actually have the input we've been expecting. Then we set it to a string and process it. Finally we create the response.
 
Then the response  will be handled using JavaScript
document.getElementById("ResponseSpanID").innerHTML = xmlhttp.responseText;
and presented to the user.
 
The following images describe the actions.
 
ajax GET form
 
ajax GET response
 
 
 
We could easily send more than one variable since urls support multiple variables, e.g.  http://dotnethints.com/blog?search=code&page=2
 

AJAX and POST

This is how we use GET. POST is quite similar. Let's create a form where the user will submit her email and send a question. This would not be a good example of GET request since we are sending data for the server to store.
 
Here's the HTML code
 
<div>
        <table>
            <tr><td colspan="2">Please insert your email so we can answer your question.</td></tr>
            <tr><td> Email: </td><td><input type="text" id="EmailInputID" /></td></tr>
             <tr><td> Question:</td><td> <input type="text" id="QuestionInputID" /></td></tr>
             <tr><td/><td> <button onclick="submitQuestion()">Submit</button></td></tr>
        </table>
        <span id="ConfirmSpanID" />
    </div>
 
ajax POST
 
and the JavaScript code
 
function submitQuestion() {
            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("ConfirmSpanID").innerHTML = xmlhttp.responseText;
                }
            }
           xmlhttp.open("POST", "AjaxAdvanced.aspx", true);
           xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
           var email = document.getElementById("EmailInputID").value;
           var question = document.getElementById("QuestionInputID").value;
           var postVariables = "email=" + email + "&question=" + question;
           xmlhttp.send(postVariables);
}
 
The actual difference between GET and POST in the script is right here:
           xmlhttp.open("POST""AjaxAdvanced.aspx"true);
           xmlhttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
           var email = document.getElementById("EmailInputID").value;
           var question = document.getElementById("QuestionInputID").value;
           var postVariables = "email=" + email + "&question=" + question;
           xmlhttp.send(postVariables);
 
First we use the "POST" keyword, then we need to set the RequestHeader and finally insert the variable in the send() method. The rest is quite the same.
 
Similar this is the server page.
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxAdvanced.aspx.cs" Inherits="Ajax_AjaxAdvanced" %>
 
 
using System;
 
public partial class Ajax_AjaxAdvanced : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //POST uses Form variables
        if (Request.Form["email"] != null && Request.Form["question"] != null)
        {
            string email = Request.Form["email"].ToString();
            string question = Request.Form["question"].ToString();
 
            //Submit email and question
 
            Response.Write("Form submitted");
        }
    }
}
 
We check for null variables and then get our data from Request.Form. Then (supposing that our cool site never fails) we show a message to the user.
 
Here's the result.
 
ajax POST
 
ajax POST response
 
 
 
 
 
 

Summary

We had a look at what GET and POST HTTP Request Methods stand for. GET is used when we want to ask for data and POST when we want to send data. We can combine both methods with AJAX and create advanced AJAX stuff by sending input to server pages.
 

Πίσω στο BlogΠροηγούμενοΕπόμενο

Σχόλια



    Γράψε το σχόλιό σου
    Όνομα: