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.post, jQuery.ajax does not work for it.

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

var url = “http://yourdomain.com/sample-page.aspx?callback=?”;

jQuery(document).ready(

    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:

{‘name’:’abc’,’price’:’44’}

 

 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 asp.net 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’});’;

Advertisements

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)
{
sbLog.AppendLine(e.Message);
}

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

SqlCommand cmd = new SqlCommand();

if (cn.State != ConnectionState.Open)
cn.Open();

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

cmd.CommandType = CommandType.StoredProcedure;

cmd.ExecuteNonQuery();

 

‘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:

CREATE PROCEDURE GETPRODICTS

@Keyword nvarchar(20),

@CNT int OUTPUT

AS

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

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

GO

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;

 

cmd.Parameters.Add(tmpParam);

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

                if (rdr.HasRows)

                {  xTbl.Load(rdr);  }

                rdr.Close();

                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
https://siddharthboraniait.wordpress.com/2013/09/11/show-current-date-using-javascript-in-web-browserclient-side-date-in-web-browser

 

How to make custom Task Scheduler in asp.net c# using thread
https://siddharthboraniait.wordpress.com/2013/09/06/howto-make-custom-task-scheduler-in-asp-net-csharp-using-thread

 

Introduction to Andriod – First step towards Andriod application development
https://siddharthboraniait.wordpress.com/2011/07/18/know-andriod-introduction-to-andriod

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 (
SELECT
ROW_NUMBER() OVER(order by ProductName ASC ) as RowNum,
ProductId,ProductName
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,
$.each
is use for looping through all logical record in json data.

jQuery.ajax(
            {
                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;
                    });

                    jQuery("#d1").html(strResult);
                }
            }
        );

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).

 

[WebMethod]

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];

objfilestream.Read(arrDocumentContents,0,len);

objfilestream.Close();

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=”http://tempuri.org/”>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.

Syntax:

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

Example:

<IMG SRC=”data:image/gif;base64, R0lGODlhCAAFAIABAMaAgP///yH5BAEAAAEALAAAAAAIAAUAAAIKBBKGebzqoJKtAAA7″ />

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
https://siddharthboraniait.wordpress.com/2013/09/11/show-current-date-using-javascript-in-web-browserclient-side-date-in-web-browser

 

How to make custom Task Scheduler in asp.net c# using thread
https://siddharthboraniait.wordpress.com/2013/09/06/howto-make-custom-task-scheduler-in-asp-net-csharp-using-thread

 

Introduction to Andriod – First step towards Andriod application development
https://siddharthboraniait.wordpress.com/2011/07/18/know-andriod-introduction-to-andriod