In one of the previous article we mentioned how to use the Ajax API available in JQuery to perform Ajax operations. We demonstrated the use by setting the dataType as "json" and invoking a server side method. In this article we will use JQuery Ajax API to send plain text to a server side method.
Why Send Text?
Why send text when we can easily send data in json format? There are some scenarios where you only want to send simple plain text to the server side web method. This also includes sending comma separated list.
Requirement:
The only requirement of using JQuery Ajax API is to download the JQuery library (FREE) from www.jquery.com. Once, you have download the library add it to your project and reference it in your ASPX page.
Scenario:
We are going to send some custom text entered in a TextBox to a server side web method using JQuery Ajax API and return some custom text from that method. Let's check out the server side method first.
As, you can see in the above code the GetCategoryName method is pretty simple! It takes categoryName as an argument and return a constant value of "Beverages" to the client.
Now, let's move to the client side code:
The above code is fired when a user clicks a button. The explanation of the above parameters is given below:
type: The type can be POST or GET
dataType: The type of request. This can be json,text,xml etc
url: The url of the method to be invoked
data: The data to be sent as a parameter to the method defined in the url
success: The callback function which will be fired when the Ajax operation is successful
You might have noted that we are sending "some value" as a constant value to the GetCategoryName function. When you run this example and click on the button you will notice that an error has occurred. FireBug shows the error as shown in the following screenshot.
The error shows that the parameter "categoryName" is missing. The parameter "categoryName" is the exact same name we assigned to the parameter in our server side GetCategoryName method. This problem can be easily resolved from the client side. Check out the following code:
Did you notice the change? We added a parameter with the same name as in the server side method to the data attribute of the JQuery Ajax call. Now, the parameter will be passed to the GetCategoryName method and everything would work as expected.
Recommended Reading:
A Look into JQuery Ajax API
Conclusion:
Although most of the time we will be passing and retrieving data in json format but sometimes it is quite reasonable to send in plain text values. In one of the future articles we will demonstrate how sending plain text saved us bandwidth and got the job done.