Tag Archives: JQuery

Read JSON using JavaScript

Hi Guys,

Here we are going to have a simple code which will show how to read data from JSON and fill Dropdown. All will be done through JavaScript.

Very first thing we are going to make one JSON object with Weather Information city wise.

After that we have made some functions which will be used to fill the dropdown list for City and Weather.

<script language="javascript" type="text/javascript">

var objJSON = { "weatherdetails":
    {
        "weatherreport":
            [
                {"city": "Mumbai", "weather": "32" },
                {"city": "Delhi", "weather": "28" },
                {"city": "Chennai", "weather": "34" },
                {"city": "Kolkata", "weather": "26" }
            ]
    }
};

var obj = eval(objJSON.weatherdetails);

function showJSON(){
    for(var i=0;i<obj.weatherreport.length;i++){
    alert(obj.weatherreport[i].city + "----" + obj.weatherreport[i].weather);
    }
}

function LoadCity(){
    var optionCity = "Select One City";
    document.getElementById("ddlCity").options[0] = new Option(optionCity, "0");
    for(var i=0;i<obj.weatherreport.length;i++){
        document.getElementById("ddlCity").options[i+1] = new Option(obj.weatherreport[i].city, obj.weatherreport[i].city);
    }

}

function LoadWeather(){

    var optionWeather = "Select One Weather";
    document.getElementById("ddlWeather").options[0] = new Option(optionWeather, "0");
    for(var i=0;i<obj.weatherreport.length;i++){
        document.getElementById("ddlWeather").options[i+1] = new Option(obj.weatherreport[i].weather, obj.weatherreport[i].city);
    }
}

function showWeather(ctrl){
    var strCity = ctrl.options[ctrl.selectedIndex].value;
    var strWeather = document.getElementById("ddlWeather");
    for(var i = 0; i < strWeather.length; i++)
       {
        if(strWeather.options[i].value == strCity){
                  strWeather.selectedIndex = i;
            return;
        }

       }
}

</script>

 

Below is the HTML code:

<div>
       <input type="button" id="btnShow" value="Show City and Weather" onclick="showJSON();" /></div>
<div>
       <input type="button" id="btnLoadCity" value="Load City" onclick="LoadCity();" />
       <select id="ddlCity" onChange="showWeather(this);"></select>
<div id="dvCity"></div>
</div>
<div>
        <input type="button" id="btnLoadWeather" value="Load Weather" onclick="LoadWeather();" />
        <select id="ddlWeather"></select>
</div>

 

Below is the code which used to load the dropdown list on onload function.

<script language="javascript" type="text/javascript">
function loadData(){
    LoadCity();LoadWeather();
}

window.onload = loadData;
</script>

 

This is final output of above code :

JSON

Advertisements

How to post Data using JQuery..

Guys,

I have Implemented JQuery’s “$.post” method so thought this can be helpful for someone..

putcomments1

This is how our application look like. Once we put our comments in box and press Quick Comments button it will call JQuery $.post method to post User entered data to Server and will save it in DB table.

So here are the steps to make a comment posting code :

First we need to include JQuery files (Update Script file path according to your directory structure):

<script src=”Scripts/jquery-1.4.1.min.js” type=”text/javascript”></script>
<script src=”Scripts/jquery-1.4.1-vsdoc.js” type=”text/javascript”></script>
<script src=”Scripts/jquery-1.4.1.js” type=”text/javascript”></script>

Following is the HTML code which will give you above output (Ofcourse this is not full code with css and all)

<div>
                        <%   1: # DataBinder.Eval(Container.DataItem, "Postcontent")
%>
                        <br />
                        <div align="left">
                            <a href="#" class="comment_button" accessid='<%# DataBinder.Eval(Container.DataItem, "Postid") %>'
                                id='btnComment_<%# DataBinder.Eval(Container.DataItem, "Postid") %>'>Quick comment</a>
                        </div>
                        <div class='panel' id='slidepanel<%# DataBinder.Eval(Container.DataItem, "Postid") %>'>
                            <textarea cols="50" rows="2" id='txtComment_<%# DataBinder.Eval(Container.DataItem, "Postid") %>'></textarea><br />
                            <input type="button" value=" Quick comment " accessid='<%# DataBinder.Eval(Container.DataItem, "Postid") %>'
                                id='btnCommentSubmit_<%# DataBinder.Eval(Container.DataItem, "Postid") %>' class="comment_submit" />
                        </div>
                        <div id='postedComment_<%# DataBinder.Eval(Container.DataItem, "Postid") %>'>
                        </div>
                    </div>

 

Now time to write some code on Quick Comment button which actually saves the data into database. So following is the JQuery code which will do this task for us.
$(document).ready(function(){
        $(function () {
            $('.comment_submit').click(function () {
                if (isUserLoggedIn == "True" || isUserLoggedIn == "true") {

                    var element = $(this);
                    var id = element.attr("accessid");
                    var commentText = $('#txtComment_' + id).val();
                    if (commentText == "") {
                        showNotification({
                            message: "Please put some comments to post.",
                            type: "error",
                            autoClose: true,
                            duration: 3
                            });
                     return false; }
                    $.post(
                    'Global/AjaxRequestData.aspx',
                    { mode: "comment", comment: commentText, Commentpostid: id },
                    function (data) {
                        var retVal1 = $('#lblMessage', data).html();
                        var retVal2 = $('#lblReturnValue', data).html();
                        var $readcmnt = $('#btnViewComment_' + id);
                        if (retVal1 == "1") {
                            //$('#postedComment_' + id).addClass("success");
                            //$('#postedComment_' + id).html("Comment posted successfully. You can see more comments by clicking on <b>Read comments</b> link.").show();
                            /*$('.dvUserAlerts').slideDown('slow', function(){
                                $('.dvUserAlerts').html("Comment posted successfully. You can see more comments by clicking on <b>Read comments</b> link.");
                            });*/

                            showNotification({
                            message: "Comment posted successfully. You can see more comments by clicking on <b>Read comments</b> link.",
                            type: "success",
                            autoClose: true,
                            duration: 3
                            });

                            /*$readcmnt.stop();
                            $readcmnt.css("background-color", "red");
                            $readcmnt.css("color", "white");*/
                        } else {

                        showNotification({
                            message: "Some problem in posting your comments please try after some time.",
                            type: "error",
                            autoClose: true,
                            duration: 3
                            });

                            /*$('#postedComment_' + id).addClass("error");
                            $('#postedComment_' + id).html("Some problem in posting your comments please try after some time.").show();*/

                        }
                        $("#slidepanel" + id).slideUp(300);
                        /*$('#postedComment_' + id).delay(10000).slideUp(1400);*/
                        $('#txtComment_' + id).val("");
                    }
                    );
                    //$('#postedComment_' + id).load('global/popup.aspx');
                } else {

                    $('#dvReadComments').load('global/popup.aspx?mode=login');
                    ShowModalPopup('dvComments'); return false;
                        //showLogin();
                }
            });
        });
        });

 

You will notice in above code there is one function I have called with name “showNotification” this is one my custom made JS function which shows the alert messages, although you can also use simple Javascript alert for the same.

Sorry : I have not actually removed some commented code.. 🙂

In above code main part is call to another aspx page which actually contains the code logic of saving this comment. Along with this “post” request we are also passing some parameters named as mode, comment, commentText, Commentpostid which will carry respective values.

$.post(
          'Global/AjaxRequestData.aspx',
          { mode: "comment", comment: commentText, Commentpostid: id },

 

The above used “AjaxRequestData.aspx’” page will contain some normal conditions as shown in below code, as we have send our parameters through POST method we need to catch these parameters with “Request” Object also shown in below code. Here your actual saving code logic will come which will save your data..

This “AjaxRequestData.aspx’” page will also contains some HTML code which contains some elements used to actually catch the response from server.

<pre>
            <asp:Label ID="lblMessage" runat="server" Style="display: none"></asp:Label>
            <asp:Label ID="lblReturnValue" runat="server" Style="display: none" EnableViewState="false"
                Text=""></asp:Label>
 </pre>
if (Request["mode"] != null && Request["mode"] == "comment")
{
    string Commenttext = Request["comment"].ToString();

    lblMessage.Text = "Your Save Function will come here return some values (0 or 1)"
    lblReturnValue.Text = lblMessage.Text;
 }

 

 

So Guys this was all code through which you can make a comment posting control using JQuery.

Hope this will help you out 🙂

Please do let me know If you need any clarification on this code.

LINQ Operations

.NET Language-Integrated Query (LINQ) defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable-based information source.

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="JSON.About" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        LINQ Demo :-
    </h2>
       <table style="width:100%;">
        <tr>
            <td>
                <asp:Button ID="btngetdata" runat="server" onclick="btngetdata_Click" 
                    Text="Fill with LINQ" />
            </td>
            <td>
                <asp:DropDownList ID="ddlgetdata" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
                    Text="Declaritive Short Hand " />
            </td>
            <td>
                <asp:DropDownList ID="ddlshorthand" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button3" runat="server" onclick="Button3_Click" 
                    Text="Lambda Expressions and Expression Trees" />
            </td>
            <td>
                <asp:DropDownList ID="ddlextressiontree" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button4" runat="server" onclick="Button4_Click" 
                    Text="LINQ anonymous methods" />
            </td>
            <td>
                <asp:DropDownList ID="ddlanonymous" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnwhere" runat="server" onclick="btnwhere_Click" 
                    Text="where" />
            </td>
            <td>
                <asp:DropDownList ID="ddlwhere" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btndatatable" runat="server" onclick="btndatatable_Click" 
                    Text="LINQ with DataTable" />
            </td>
            <td>
                <asp:DropDownList ID="ddlDatatable" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</asp:Content>

Here we are having an Array on which we are going to Implement LINQ :

string[] names = { "Abhishek", "Rohit", "Mayank", 
                       "Rider", "Lucky", "Utkarsh", 
                       "Lakhan", "Manish" };

Below is the Source code how to fill a Dropdown list using Simple LINQ :-

protected void btngetdata_Click(object sender, EventArgs e)
{
    IEnumerable<string> data = from d in names
			       where d.Length < 6
			       select d.ToUpper();
    foreach (string da in data)
    {
	ddlgetdata.Items.Add(da.ToString());
    }
}

This above query can also be written as below, this approach is called Method based :-

protected void methodbased_Click(object sender, EventArgs e)
{
    IEnumerable<string> str = names
       .Where(s => s.Length < 6)
       .OrderBy(s => s)
       .Select(s => s.ToUpper());

    foreach (string da1 in str)
    {
	ddlshorthand.Items.Add(da1.ToString());
    }
}

Lambda Expressions and Expression Trees (Func delegate type) :-

protected void Button3_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = s => s.Length < 6;
    Func<string, string> Order = s => s;
    Func<string, string> sel = s => s.ToUpper();

    IEnumerable<string> d = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string i in d)
    {
	ddlextressiontree.Items.Add(i);
    }
}

We can also write the above method using anonymous methods (Delegates) like below :-

protected void Button4_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = delegate(string s)
    {
	return s.Length < 6;
    };

    Func<string, string> Order = delegate(string s)
    {
	return s;
    };

    Func<string, string> sel = delegate(string s)
    {
	return s.ToUpper();
    };

    IEnumerable<string> query = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string s in query)
    {
	ddlanonymous.Items.Add(s);
    }
}
protected void btnwhere_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    IEnumerable<string> query = names.Where(s => s[0] == 'A');
    foreach (string z in query)
    {
	ddlwhere.Items.Add(z);
    }
}

Now we are going to see how to implement LINQ on DataTable, However DataTable is not an IEnumerable type and LINQ is only work with IEnumerable Types.
So here we need to convert this DataTable to IEnumerable Types and then we can apply LINQ over it.

We can have a DataTable as follows :-

static DataTable GetTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Id", typeof(int));
    table.Columns.Add("Address", typeof(string));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    table.Rows.Add(1, "Indore", "Abhishek", DateTime.Now);
    table.Rows.Add(2, "Pune", "Rohit", DateTime.Now);
    table.Rows.Add(3, "Hydrabad", "Mayank", DateTime.Now);
    table.Rows.Add(4, "Mumbai", "Rider", DateTime.Now);
    table.Rows.Add(5, "Bangalore", "Lucky", DateTime.Now);
    return table;
}

In below code we have used “AsEnumerable()” method to make DataTable of IEnumerable Type.

protected void btndatatable_Click(object sender, EventArgs e)
{
    //AsEnumerable() Used here to convert Datatable (DataTable is NOT IEnumerable Type) in to IEnumerable type so that we can apply LINQ in it.
    var query = from data in GetTable().AsEnumerable()
		where data.Field<int>("Id") > 2 && data.Field<string>("Name").StartsWith("M")
		select new
		{
		    Name = data.Field<string>("Name"),
		    Id = data.Field<int>("Id")
		};

    foreach (var v in query)
    {
	ddlDatatable.DataTextField = v.Name.ToString();
	ddlDatatable.DataValueField = v.Id.ToString();
	ddlDatatable.Items.Add(v.Name.ToString());
    }
}

LINQ Demo

Note :-
As per my thinking this LINQ can be very usefull for small data to Operate on.. If we retrieve data from DB in bulk and keep it in memory so that we can apply LINQ on that data that is not a good option..