Tuesday, January 11, 2011

HOW TO: Use JSON with Ajax & Classic ASP

JSON stands for JavaScript Object Notation and it is just a standard object description that can be adopted by all programming languages. We can also assume it as a data interchange format between different programming languages. Unlike XML, JSON is lightweight.
You can read more about JSON at http://www.json.org/


I would like to explain simple example that will retrieve person name from server and display the greeting message to the user. I'll use classic asp for server side page, and javascript and ajax to query the server side page.


GetMessage.asp

This is the server side classic asp page and when this page is requested, it will return JSON object.
<%
    'This will return the JSON object as a response
    'Comment below line to see this page result in browser
    Response.AddHeader "Content-Type", "application/json"
%>
<!-- #include file="JSON_2.0.4.asp" -->
<!-- #include file="JSON_UTIL_0.1.1.asp" -->
<%
    Dim Com, SQL
    'This is just a helper function to open database connection
    Call fnOpenDBConnection("dbName",Com)
    'This query simply return first name and last name
    SQL = "Select FirstName,LastName From PersonTable"
    'This to make sure any un-related responses to be clear
    Response.Clear
    'This utility function in JSON_UTIL_0.1.1.asp accept SQL query and connection object and return JSON object. Extra Flush function directly write the response JSON object to response stream
    QueryToJSON(Com, sql).Flush
    'Close database connnection
    Call fnCloseDBConnection(Com)
End Function
%>

You can download ASP to JSON .asp files from

When you access this page in the browser, it will show similar to this:
[{"FirstName":"Kyaw","LastName":"Lwin"}]
But remember to comment Content-Type header to be able to view the page in browser.

Greeting.html
This html page will query the server side page and it will show the result back to the user as a alert.
<html>
<head>
<script src="jquery.js">
<script type="text/javascript" language="javascript">
     'query the server side page with ajax
     'if the result is success, show alert message together with the result
     'dataType:"json" tells that expected response from server is JSON
     $.ajax({url:"GetMessage.asp",type:"POST",  
          success:function(result){
               alert('Hello ' + result[0].FirstName + ' ' + result[0].LastName);
          },dataType:"json"});

</script>
</head>
<body>
This is JSON test page.
</body>
</html>

You can download jquery.js from
http://jquery.org/

No comments:

Post a Comment