Wednesday, 26 March 2014

How to read and get JSON data using Jquery?

Description:

Welcome to Jqueryjohn.com.

In this article, I will explain how to read and get JSON data using Jquery and AJAX.  

JSON is nothing but text format that is easy to read and write. It’s like XML, fast and easy to parse.

JSON is lightweight text interchange format, smaller than XML.

When the document is ready, use AJAX request to read and Get the JSON values.

Specify type as ‘POST’ and datatype as ‘json’.

Success parameter takes JSON data.

success: function (response) {
            var jsonval = eval('(' + response.d + ')');
            for (var i = 0; i < jsonval.length; i++) {
               var city = jsonval[i].City_Name;
            }
}

In the below example, I am converting dataset values into JSON.

Example program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnReadGetJson').click(function () {
                $.ajax({
                    type: "POST",
                    url: "ReadXml.aspx/GetJsonData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $("#divArea").html("<b><u>Cities retreived from the database are</u></b><br />");
                        var city = "";
                        var jsonval = eval('(' + response.d + ')');
                        var citylength = jsonval.length;
                        if (citylength > 0) {
                            for (var i = 0; i < citylength; i++) {
                                var city = jsonval[i].City_Name;
                                $("#divArea").append('<li>' + city + '<li>');
                            }
                        }
                    },
                    error: function () {
                        alert("Failure");
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divArea">
        <asp:Button ID="btnReadGetJson" runat="server" Text="Read & Get JSON Data" />
        <br />
    </div>
    </form>
</body>
</html>

Code behind:

 [System.Web.Services.WebMethod]
 public static string GetJsonData()
 {
       SqlConnection con = new SqlConnection("Data Source=192.169.1.151;Initial Catalog=Example;User ID=sa;Password=welcome3#;");
       con.Open();
       SqlCommand cmd = new SqlCommand("select City_Name from City", con);
       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataTable ds = new DataTable();
       da.Fill(ds);
       string obj = GetJson(ds);
       return obj;
 }

public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName.Trim(), dr[col]);
                }
                rows.Add(row);
}
return serializer.Serialize(rows);
}

The above program reads the JSON data and updates with the page without postback via JQuery AJAX.


Read Json data using jquery, jquery to read Json data, how to read and parse Json data, load Json data using Jquery Ajax, retrieve data from Json using jquery

How to read and get XML file using Jquery?

Description:

Welcome to Jqueryjohn.com.

In this article, I will explain how to read and get XML data using Jquery and AJAX.  

Make sure the Xml file which we are going to read it’s free of errors.

When the document is ready, use AJAX request to read and Get the values of the Xml data.

$.ajax({
          type: "GET",
          url: "JQueryJohn.xml",
          dataType: "xml",
          success: function (response) {
          },
          error: function () {
              alert("Failure");
          }
      });

Specify type as ‘GET’ and datatype as ‘xml’.

Success parameter takes the data from the xml file.

success: function (response) {
         $(response).find('Tutorials').each(function () {
               var lesson = $(this).find('Lesson').text();
               var author = $(this).find('Author').text();
         });
}

Use find() method, read each node and get the values.

Example program:

JQueryJohn.xml:

<?xml version="1.0" encoding="utf-8" ?>
<JQueryJohn.com>
       <Tutorials>
              <Lesson>Introduction and Fundamentals of JQuery</Lesson>
              <Author>JQueryJohn</Author>
       </Tutorials>
       <Tutorials>
              <Lesson>Selectors and Attributes in JQuery</Lesson>
              <Author>JQueryJohn</Author>
       </Tutorials>
       <Tutorials>
              <Lesson>Animation and Effects in JQuery</Lesson>
              <Author>JQueryJohn</Author>
       </Tutorials>
       <Tutorials>
              <Lesson>Events and Methods in JQuery</Lesson>
              <Author>JQueryJohn</Author>
       </Tutorials>
       <Tutorials>
              <Lesson>AJAX with JQuery</Lesson>
              <Author>JQueryJohn</Author>
       </Tutorials>
</JQueryJohn.com>

ReadXMLData.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnReadGetXmlFile').click(function () {
                $.ajax({
                    type: "GET",
                    url: "JQueryJohn.xml",
                    dataType: "xml",
                    success: function (response) {
                        $("#divArea").html("<b><u>Jqueryjohn.com contains the following lessons with code snippets</u></b><br />");
                        $(response).find('Tutorials').each(function () {
                            var lesson = $(this).find('Lesson').text();
                            var author = $(this).find('Author').text();
                            $("#divArea").append('<li>' + lesson + " , Author: " + author + '<li>');
                        });
                    },
                    error: function () {
                        alert("Failure");
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divArea">
        <asp:Button ID="btnReadGetXmlFile" runat="server" Text="Read & Get XML File" />
        <br />
    </div>
    </form>
</body>
</html>

The above program reads the xml file and updates with the page without postback via JQuery AJAX.


Read xml file using jquery, jquery to read xml file, how to read and parse xml data, load xml file using Jquery Ajax, retrieve data from xml file using jquery

How to create simple jquery Popup box using Jquery?

Description:

Welcome to Jqueryjohn.com.

In this article, I will explain how to create simple popup box without any plugin using Jquery and CSS.  

In the previous article, I have used window.open() and window.ShowModalDialog() method for creating popup window.

There are lot of Popup plugins are available. I don’t think that a jquery plugin is required for this. We can easily achieve with simple javascript code and css.

We can simply create popup box using fadeIn () and fadeOut () method.

To open popup window at the center of the screen, use the following CSS property.

left: 35%;
top: 35%;
position: fixed;

Adjust the top and left property based on your popup div width to make it center of the screen.

Example program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <style type="text/css">
        #PopupPage
        {
            border: 3px solid #ccc;
            left: 35%;
            top: 35%;
            position: fixed;
            width: 235px;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#PopupPage').fadeOut();
            $('#btnPopup').click(function () {
                $('#ParentPage').fadeOut(1000);
                $('#PopupPage').fadeIn(1000);
                return false;
            });
            $('#btnCancel').click(function () {
                $('#PopupPage').fadeOut(1000);
                $('#ParentPage').fadeIn(1000);
                return false;
            });
            $('#btnLogin').click(function () {
                alert("Welcome");
                $('#ParentPage').fadeOut(1000);
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="ParentPage">
        <asp:Button ID="btnPopup" runat="server" Text="Open Popup" />
    </div>
    <div id="PopupPage" style="display: none;">
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblUserName" runat="server" Text="UserName"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnLogin" runat="server" Text="Login" />
                </td>
                <td>
                    <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


Creating jquery popup div, open popup window using Jquery, Using Jquery to open a Popup window, Popup div using Jquery, Open Jquery Popup window