CameTooFar

A Nerd's False Positive.

Send bulk data using Ajax using POST


This post is related to my previous post - A Forgotten Story – Ajax in ASP.NET using JavaScript. So, In case of any doubt, please refer the post. This post explains how to send bulk data from client-side to server-side via Ajax.

Recently, in one of my application, I’s trying to send some XML data from client-side to server-side through Ajax, using the default GET method. As long as the size of the xml data is minimal, it works fine. But, when I tried to send a lengthy data using the GET method, then the parameter/argument to which the data assigned appears to be empty, in the server-side.

A small digging took me here.

This is because in Internet Explorer, the GET method can only send a limited set of data to the server-side and is restricted to 2083 characters. To overcome this limitation we can use POST method for sending huge data to the server-side, in the form of name-value pairs. For this, the XMLHttpRequest has a method: send(args) which accepts arguments, which will be posted/send to the server.

Another thing to note is, since you are sending the request through POST, you cannot use Request.QueryString to get the argument’s value. Instead you’ve to use Request.Form[argument_name].

Last but not the least, you’ve to set the RequestHeader during Ajax call as below, else the value in the parameters will be empty.

   1: xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   2: xmlHttp.setRequestHeader("Content-length", args.length);

The entire code looks like

Client-Side

   1: <script type="text/javascript">
   2:     function sendViaAjax() {
   3:  
   4:         // URL to make the Ajax call
   5:         var url = 'Test.aspx';
   6:  
   7:         // Arguments (with BULK DATA) that is to be passed to the server-side
   8:         var args = 'arg1=somedata&arg2=somebulkdata';
   9:  
  10:         // Creates an Ajax call object
  11:         var xmlHttp = new XMLHttpRequest();
  12:  
  13:         // Specify POST method & URL to connect
  14:         xmlHttp.open("POST", url, true);
  15:  
  16:         // Callback function to response from Server
  17:         xmlHttp.onreadystatechange = function () {
  18:             if (xmlHttp.readyState == 4) {
  19:                 if (xmlHttp.status == 200) {
  20:                     alert(xmlHttp.responseText);
  21:                 }
  22:                 else {
  23:                     alert('Status: ' + xmlHttp.status + ' Response:' + xmlHttp.responseText);
  24:                 }
  25:             }
  26:         };
  27:  
  28:         xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  29:         xmlHttp.setRequestHeader("Content-length", args.length);
  30:  
  31:         // Send Ajax request to Server, along with Arguments
  32:         xmlHttp.send(args);
  33:     }
  34: </script>


Server-Side

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     string arg1 = Request.Form["arg1"];
   4:     string arg2 = Request.Form["args2"];
   5:     
   6:     // Some operations comes here
   7: }


Yup! That’s it.

Now you know how to send bulk data through Ajax. By the way, this article is aimed at Internet Explorer users.

If you get any error-code like 12030/12031, then please do refer to List of Windows Error Messages.

Hope this helped.

Thanks and Happy Ajaxing.

Ajax Error - Question marks on sending Foreign Language


Yup! So that’s the problem when you switch to Foreign Languages! This post is related to my previous post – A Forgotten Story – Ajax in ASP.NET using JavaScript.

Last day, I’s trying to send Chinese characters over the wire through Ajax. Surprisingly, I received every Chinese characters at the server-side as questions marks.

A mock-up looks like:

encoding

After spending few hours with the academic basics, the problem was pin-pointed.

The request sending from the client-side was not encoded, which was the reason for this weird behavior. I slightly modified the Ajax code to encode the value from the TextBox and the problem was solved!

You can use either of the below JavaScript function to achieve it:

  1. encodeURI

    This function is used to encode URI. It encodes special characters (except / , ? : @ & = + $ #)
  2. encodeURIComponent

    This function encodes URI component, including the characters excluded by encodeURI

And, a modified code-segment looks like

decode

Hope there is no question-marks in your Request.

Happy Encoding!

A Forgotten Story - Ajax in ASP.NET using JavaScript


This post explain how to perform an Ajax call in an asp.net page, using native Ajax code. There is nothing New with this post, its typically an old school note. But, you can still see developers who don’t know how to make a raw/plain Ajax call in asp.net, but knows how to perform Ajax call using jQuery, ASP.NET AJAX or any other frameworks.

In a nut-shell, frameworks like jQuery and ASP.NET AJAX are wrappers written over the raw/plain Ajax. Of course, they make our work easy and simple, but these frameworks hides the core concept. Hence an average amount don’t understand what happens really under the hoods and will gaze while troubleshooting a web application.

Ajax is not a technology, but a technique for creating fast and dynamic interactive web pages.

In this post, I’ll demonstrate a simple example on how to send data from client-side to server-side, using Ajax and to get a response (Callback) from server-side.

[Design]

Server-side

[Ajax Script]

This is the Ajax script that send the details to the server.

<script type="text/javascript">
    function sendViaAjax() {
 
        // Build URL to make Ajax call
        var url = "Test.aspx?name=" + document.getElementById("txtName").value;
 
        // Creates an Ajax call object
        var xmlHttp; = new XMLHttpRequest();
 
        // Specify URL to connect
        xmlHttp.open("GET", url, true);
 
        // Callback function to handle response from Server
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    alert(xmlHttp.responseText);
                }
            }
        };
 
        // Send Ajax request to Server
        xmlHttp.send();
    }
</script>

where,

XMLHttpRequest XHR is an API in JavaScript, which allows to send both HTTP/HTTPS requests directly to the web server and load the server response data (plain-text/xml) directly back into the script
   
open Specifies:

a. request type (GET/POST)
b. URL to the server page
c. connection type (Async: true, Sync: false)
   
send Send the request to server
   
onreadystatechange Sets the callback function to handle the response from server
   
readyState Holds the status of XHR:

0:   request not initialized
1:   server connection established
2:   request received
3:   processing request
4:   request completed & response is ready
   
status Retrieves the HTTP status-code of the response

200: OK
404: Page not found
   
responseText Retrieves the response body as a string
   

 

[Server Side Code]

The server-side code that accepts the Ajax request and send response back to client-side looks like

protected void Page_Load(object sender, EventArgs e)
{
    string ajxValue = "Hello " + Request.QueryString["name"] + " !";
 
    Response.Write(ajxValue);   // Write the Response
    Response.End(); // End Response
}

In the above snippet, value passed from the client-side is read as QueryString and writes back to the client-side after modification.

Please note, once the response is written, we immediately calls Response.End() method. This is done so that only the ajxValue will be available in the response stream. Else, the entire html of the page will be available along with the ajxValue, in the response stream.

A sample output, without calling Response.End()looks like

ajaxresponse

The complete solution can be summed-up as

[Default.aspx]

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function sendViaAjax() {
 
            // Build URL to make Ajax call
            var url = "Test.aspx?name=" + document.getElementById("txtName").value;
 
            // Creates an Ajax call object
            var xmlHttp = new XMLHttpRequest();
 
            // Specify URL to connect
            xmlHttp.open("GET", url, true);
 
            // Callback function to response from Server
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        alert(xmlHttp.responseText);
                    }
                }
            };
 
            // Send Ajax request to Server
            xmlHttp.send();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Enter Name: "></asp:Label>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="Send To Server" onclick="sendViaAjax();" />
    </div>
    </form>
</body>
</html>

[Test.aspx]

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ajxValue = "Hello " + Request.QueryString["name"] + " !";
 
        Response.Write(ajxValue);   // Write the Response
        Response.End(); // End Response
    }
}

Hope this helped.

Happy Dynamic and Ajax Rich Programming!

Download Sample

For more details, spend some time with following links:

1. http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx
2. http://www.w3schools.com/ajax/ajax_intro.asp
3. http://en.wikipedia.org/wiki/List_of_HTTP_status_codes


Thanks