Retrieving cross-domain data by using jquery’s getJSON

Recently I found one limitation with jquery.ajax, problem was that when we want to retrieve data from other domain, Not from your current website.

Browser’s same-origin policy prevents requesting data from other domain.So jQuery.get,, jQuery.ajax does not work for it.

 One way to fetch data is by using jQuery’s getJSON method as follow:

var url = “”;


    function() {

        jQuery.getJSON(url, function (data) { alert(data.price); });      


 Here we have loaded JSON data located on another domain with JSONP callback, which can be done using the following syntax: url?callback=?.

jQuery automatically replaces the ? with a generated function name to call.


At Server side, data must be return in json format like:



 And additionally, you have to enclose your data inside function,

 For ex: dummyfunction({‘name’:’abc’,’price’:’44’});


Here ‘dummyfunction’ will be dynamic on each call to your page, and it will be passed to your dynamic page

Note callback=” in URL variable,

So if your are using then something like following will be there

Response.Write( Request.QueryString[“callback”] + “({‘name’:’abc’,’price’:’44’});”);


And with PHP, page response should be something as below,

echo $_GET[‘callback’].'({‘name’:’abc’,’price’:’44’});’;


Display SQL SERVER Message,Using InfoMessage Event from SQL SERVER, to troubleshoot stored procedure

Big stored procedures which are building QUERY dynamically according to parameters are used sometime for large web applications.

Bad luck starts when such procedure gives error, and as query itself build at run time, user may frustrates catching the right error.

Also,Debugging becomes challenging with it.

One way is to use PRINT statement at end of procedure, so when stored procedure executed it displays DYNAMIC QUERY.

In SQL Server Management studio we can easily view the printed query.

But what if you want it in ASP.NET environemt?

SqlConneciton class has
SqlConnection.InfoMessage event, which occurs, when SQL Servers returns a warning or informational message.

First create ‘SqlConnection’ object.

string connectionString = “Your Connection String…”;
SqlConnection myConn = new SqlConnection(connectionString);
Then, Relate method to event.

myConn.InfoMessage += new SqlInfoMessageEventHandler(MyConnection _InfoMessage);


Your method may look like following:
System.Text.StringBuilder sbLog = new System.Text.StringBuilder();

void MyConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)

Execute following code and test output with ‘sbLog.ToString()’.

SqlCommand cmd = new SqlCommand();

if (cn.State != ConnectionState.Open)

cmd.Connection = myConn;
cmd.CommandText = “SP_That_Prints_Query”;

cmd.CommandType = CommandType.StoredProcedure;



‘sbLog.ToString()’ will give you dynamic query generated in your stored procedure.


Output parameter in stored procedure with ExecuteReader method

Conventionally ExecuteReader method is used for returning DataReader object.

Which in turn you can use to fill DataTable.

What if you want a DataTable and some return argument from your stored procedure?

One way is explained below.

Your stored procedure will have one OUTPUT parameter , that will give you number returned form database:


@Keyword nvarchar(20),



Select * from product where productname like ‘%’ + @Keyword  + ‘%’

Select @CNT=count(*) from product where productname like ‘%’ + @Keyword  + ‘%’


And in ASP.Net Code should be like:

Int32 intCNT;

DataTable xTbl = new DataTable();

using (SqlConnection conn = new SqlConnection(connectionString))  


SqlCommand cmd= new SqlCommand();

cmd.Connection = conn;

cmd.CommandType= CommandType.StoredProcedure;

cmd.CommandText = “GETPRODUCTS”;


SqlParameter[]  tmpParam = new SqlParameter[] {

                new SqlParameter(“@keyword”, SqlDbType.NVarChar,20),

                new SqlParameter(“@CNT”, SqlDbType.Int)};


                tmpParam [0].Value =”test”;

                tmpParam [1].Direction = ParameterDirection.Output;



SqlDataReader rdr =cmd.ExecuteReader(CommandBehavior.CloseConnection);

                if (rdr.HasRows)

                {  xTbl.Load(rdr);  }


                intCNT = int.Parse(cmd.Parameters[1].Value.ToString());


Make sure you CLOSE data reader object before retrieving values from parameter.

So here you will get DataTable with records from data base  and Integer variable (intCNT)  with record count from same table.


Other Technical Stuff from Siddharth:

Show current date using Javascript in web browser(Client side date in web browser


How to make custom Task Scheduler in c# using thread


Introduction to Andriod – First step towards Andriod application development

Use ROW_NUMBER in SQL to retrive Paging specific records from table.

In SQL Server,

ROW_NUMBER() function returns number of row from result set(you have requested thru query).


Following sample query will result in only 10 records from Product table.

WITH DummyTable AS (
ROW_NUMBER() OVER(order by ProductName ASC ) as RowNum,
from ProductMaster
select * from DummyTable
where rownum>=210 AND rownum<220


Such query is useful if you want to implement paging in your web application/project and  you want to retrieve only records from table according to your current page.

json parsing in javascript with jquery

Following is simple example, that uses jquery.ajax function to request json data from any url.

and once data is received,
is use for looping through all logical record in json data.

                type: 'POST',
                url: 'http://demourl?tmp=' + Math.random(),
                dataType: 'json',
                data: 'keyword=demo&query=demoquery',
                success: function(jd) {

                    var strResult = '';

                    $.each(jd.posts, function(i, obj) {

                    var strLoop ="";

                    strLoop = strLoop +"<div class='resultrecord'>";
                    strLoop = strLoop + obj.firstname + ' ' + obj.lastname;
                    strLoop = strLoop +"</div>";

                    strResult = strResult + strLoop;


How to Read Binary Documents (in base64 binary format) by ASP.NET Web Service

Add new web service in your ASP.NET web application.

Adding a web service will create two file in your web application:

1)      ASMX FILE(For example WebService.asmx)

2)      CS FILE(in App_Code folder, like WebService.cs)

Create web method inside it as follow.  It takes document name as parameter and returns array of byte (binary data).



public Byte[] ReadDocument(string strDocumentName)


string strdocPath;

strdocPath = “D:\\TESTDIR1\\TESTDIR2″ + strDocumentName;

FileStream objfilestream = new FileStream(strdocPath,FileMode.Open,FileAccess.Read);

int docLen = (int)objfilestream.Length;

Byte[] arrDocumentContents  = new Byte[docLen];



return arrDocumentContents;



Above example reads file from a physical path on a system. You can also use Server.MapPath() for specifying virtual directory.

You can call webservice by using following like URL

http://yourdomain / WebService.asmx/ ReadDocument? strDocumentName=test.gif


Web service will return base64 binary data as follow:

<?xml version=”1.0″ encoding=”utf-8″?>

<base64Binary xmlns=””>R0lGODlhCAAFAIABAMaAgP///yH5BAEAAAEALAAAAAAIAAUAAAIKBBKGebzqoJKtAAA7</base64Binary&gt;

Display Image in html as Binary Data with Base64 encoding

In HTML, traditionally we use path of image file to specify image source in IMG tag.

However, we can give binary data as well as source in “SRC” attribute of IMG tag, and image will be display in html.


<IMG SRC=”data:image/gif;base64,<Binary Data>” />



Binary data in above line is ‘base64 encoded’ format of image.

One advantage of this method is that visitor never knows the PATH of image you have displayed.

Drawback of this point is that IE does not support this way to display image.


Other Technical Stuff from Siddharth:

Show current date using Javascript in web browser(Client side date in web browser


How to make custom Task Scheduler in c# using thread


Introduction to Andriod – First step towards Andriod application development