Humpy
Humpy

Reputation: 2002

Call back jQuery widget information from Database and display widgets in proper locations

I was finally able to save all my widget information successfully with the help from this question.

Now, I'm completely lost on how to do this, as it is the first time I've ever had to do this. I need to call back my database information to display my widgets properly.

This is my jQuery for the dashboard.

$(function () {
        $('.dragbox')
        .each(function () {
            $(this).hover(function () {
                $(this).find('h2').addClass('collapse');
            }, function () {
                $(this).find('h2').removeClass('collapse');
            })
            .find('h2').hover(function () {
                $(this).find('.configure').css('visibility', 'visible');
            }, function () {
                $(this).find('.configure').css('visibility', 'hidden');
            })
            .click(function () {
                $(this).siblings('.dragbox-content').toggle();
            })
            .end()
            .find('.configure').css('visibility', 'hidden');
        });

        $('.column').sortable({
            connectWith: '.column',
            handle: 'h2',
            cursor: 'move',
            placeholder: 'placeholder',
            forcePlaceholderSize: true,
            opacity: 0.4,
            start: function (event, ui) {
                //Firefox, Safari/Chrome fire click event after drag is complete, fix for that  
                //if ($.browser.mozilla || $.browser.safari)
                $(ui.item).find('.dragbox-content').toggle();
            },
            stop: function (event, ui) {
                ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix  
                //if (!$.browser.mozilla && !$.browser.safari)
                updateWidgetData();
            }
        })
        .disableSelection();
    });  

I am able to save to the database using the below and using a Handler and an data class.

function updateWidgetData() {
        var items = [];
        $('.column').each(function () {
            var columnId = $(this).attr('id');
            $('.dragbox', this).each(function (i) {
                var collapsed = 0;
                if ($(this).find('.dragbox-content').css('display') == "none")
                    collapsed = 1;
                //Create Item object for current panel  
                var item = {
                    id: $(this).attr('id'),
                    collapsed: collapsed,
                    order: i,
                    column: columnId
                };
                //Push item object into items array  
                items.push(item);
            });
        });
        //Assign items array to sortorder JSON variable  
        var sortorder = { items: items };

        $.ajax({
            url: "/Handlers/SaveWidgets.ashx",
            type: "POST",
            contentType: "application/json; charset=uft-8",
            dataType: "json",
            data: JSON.stringify(sortorder),
            success: function (response) {
                $("#console").html('<div class="success">Dashboard Saved</div>').hide().fadeIn(1000);
                setTimeout(function () {
                    $('#console').fadeOut(1000);
                }, 2000);
            },
            error: function (error) {
                alert("Failed passing json.");
            }
        });

The way the information looks in the database is like this..

enter image description here

Here is my aspx that shows the widgets (only showing 2 columns, and 1 widget for each for example)

<div class="column" id="column1" runat="server">
     <div class="dragbox" id="CurrentDealsWidget" runat="server" visible="false">
          <h2 style="font-size: 14pt">Current Deals per Location</h2>
          <div class="dragbox-content">
             <asp:GridView ID="gvCurrentLocationTotals" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="InternallocationID">
              //columns
              </asp:GridView>
          </div>
      </div>
 </div>
 <div class="column" id="column2" runat="server">
      <div class="dragbox" id="MonthlyDealsWidget" runat="server" visible="false ">
           <h2 style="font-size: 14pt">Total Processed Deals per Location</h2>
           <div class="dragbox-content">
                //content for the widget
           </div>
      </div>
  </div>

Now, I'm not sure how I would go about this. I need to call the information back from the tWidgets table and display in the proper sort. 0 being the first position in the column, followed by 1, 2, 3. I'm not sure if I should do this on the page load, or if it would be better to use a handler to do this process. I'm not sure where to start. The only information that I have found is how to do this in php but that is of no help to me. If anyone can point me in the right direction, that will be greatly appreciated!

EDIT: I have created a WebService that retrieves the widget information and then passes it to ajax on page load.

Web Service

public class RetrieveWidgets : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<RetrieveWidgetsDAL> GetWidgets()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
        List<RetrieveWidgetsDAL> listData = new List<RetrieveWidgetsDAL>();
        int getUserId;
        string userName = HttpContext.Current.User.Identity.Name;
        conn.Open();
        using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = @UserName", conn))
        {
            cmdGetUserId.Parameters.AddWithValue("@UserName", userName);
            getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());

            System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
        }

        using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = @UserId", conn))
        {
            cmdGetWidgets.Parameters.AddWithValue("@UserId", getUserId);
            using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
            {
                while (rdr.Read())
                {
                    RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
                    widgetDAL.Title = rdr.GetString(0);
                    widgetDAL.SortNo = rdr.GetInt32(1);
                    widgetDAL.Collapsed = rdr.GetInt32(2);
                    widgetDAL.ColumnId = rdr.GetInt32(3);
                    listData.Add(widgetDAL);
                }
            }
        }
        conn.Close();
        return listData;
    }
}

ajax

$(document).ready(function () {

        $.ajax({
            type: "Post",
            contentType: "application/json; charset=utf-8",
            url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
            dataType: "json",
            success: function (response) {
                alert(response.d);  // try using data.d
            },
            error: function (repo) {
                console.log(repo);
            },
            error: function (error) {
                $("#console").html('<div class="fail">Dashboard could no load!</div>').css('visibility', 'visible').fadeTo(600, 1);
                setTimeout(function () {
                    $('#console').delay(500).fadeTo(600, 0);
                }, 1000);
            }
        });
    });

Now, my question is, is there a way to use jQuery to place the widgets into their proper location based on the database information?

The json information looks like this..

{d:[{__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"CurrentDealsWidget", SortNo:0, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"StorePayrollWidget", SortNo:1, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"ObjectiveWidget", SortNo:2, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"ReportWidget", SortNo:0, Collapsed:0, ColumnId:2}

Upvotes: 1

Views: 386

Answers (1)

Shirish Patel
Shirish Patel

Reputation: 874

$(document).ready(function() {
        var response = '{"d":[{"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"CurrentDealsWidget", "SortNo":0, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"StorePayrollWidget", "SortNo":1, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"ObjectiveWidget", "SortNo":2, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"ReportWidget", "SortNo":0, "Collapsed":0, "ColumnId":2}]}';
        var te = JSON.parse(response)

        function sortResults(prop, asc) {
            te.d = te.d.sort(function(a, b) {
                if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            });
        }
        sortResults('SortNo', true);
        for (var i = 0; i < te.d.length; i++) {
            $('#test ul').append('<li>'+te.d[i].Title+'</li>')
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="test"><ul></ul></div>

This might help you.

I am not a c# or asp.net developer. But I seen you response it's not in proper json might be you miss to Format your response as a JSON . So I mad some changes in your JSON just place all key as string and that's mention below.

NEW Json

{
    "d":
        [
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"CurrentDealsWidget", 
                "SortNo":0, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"StorePayrollWidget", 
                "SortNo":1, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"ObjectiveWidget", 
                "SortNo":2, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"ReportWidget", 
                "SortNo":0, 
                "Collapsed":0, 
                "ColumnId":2
            }
        ]
    }

javaScript

Just add below script in your ajax's success function.

var te = JSON.parse(response)
                        function sortResults(prop, asc) {
                            te.d = te.d.sort(function(a, b) {
                                if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                                else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
                            });
                        }

                        sortResults('SortNo', true);

                        for (var i = 0; i < te.d.length; i++) {
                            $('#test ul').append('<li>' + te.d[i].Title + '</li>');
                            console.log(te.d[i])
                        }

HTML

<div id="test">
        <ul>

        </ul>
</div>

Once we working with Json then all key should be in string.

Upvotes: 4

Related Questions