Specializations

Showing posts with label XML with Jquery. Show all posts
Showing posts with label XML with Jquery. Show all posts

Friday, March 29, 2013

jQuery Mobile basics


Getting Started with jQuery Mobile

jQuery Mobile provides a set of touch-friendly UI widgets and an AJAX-powered navigation system to support animated page transitions. Building your first jQuery Mobile page is easy. Here's how:

Create a basic page template

Pop open your favorite text editor, paste in the page template below, save and open in a browser. You are now a mobile developer!
Here's what's in the template. In the head, a meta viewport tag sets the screen width to the pixel width of the device and references to jQuery, jQuery Mobile and the mobile theme stylesheet from the CDN add all the styles and scripts. jQuery Mobile 1.2 (1.2.0) works with versions of jQuery core from 1.7.0 to 1.8.2.
In the body, a div with a data-role of page is the wrapper used to delineate a page, and the header bar (data-role="header") and content region (data-role="content") are added inside to create a basic page (these are both optional). These data- attributes are HTML5 attributes used throughout jQuery Mobile to transform basic markup into an enhanced and styled widget.

<!DOCTYPE html> 
<html> 
<head> 
 <title>My Page</title> 
 <meta name="viewport" content="width=device-width, initial-scale=1"> 
 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
 <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
 <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head> 
<body> 

<div data-role="page">

 <div data-role="header">
  <h1>My Title</h1>
 </div><!-- /header -->

 <div data-role="content"> 
  <p>Hello world</p>  
 </div><!-- /content -->

</div><!-- /page -->

</body>
</html>

Add your content

Inside your content container, you can add any standard HTML elements - headings, lists, paragraphs, etc. You can write your own custom styles to create custom layouts by adding an additional stylesheet to the head after the jQuery Mobile stylesheet.

Make a listview

jQuery Mobile includes a diverse set of common listviews that are coded as lists with a data-role="listview"added. Here is a simple linked list that has a role of listview. We're going to make this look like an inset module by adding a data-inset="true" and add a dynamic search filter with the data-filter="true" attributes.

<ul data-role="listview" data-inset="true" data-filter="true">
 <li><a href="#">Acura</a></li>
 <li><a href="#">Audi</a></li>
 <li><a href="#">BMW</a></li>
 <li><a href="#">Cadillac</a></li>
 <li><a href="#">Ferrari</a></li>
</ul>

Add a slider

The framework contains a full set of form elements that automatically are enhanced into touch-friendly styled widgets. Here's a slider made with the new HTML5 input type of range, no data-role needed. Be sure to wrap these in a formelement and always properly associate a label to every form element.

<form>
   <label for="slider-0">Input slider:</label>
   <input type="range" name="slider" id="slider-0" value="25" min="0" max="100"  />
</form>

Make a button

There are a few ways to make buttons, but lets turn a link into a button so it's easy to click. Just start with a link and add adata-role="button" attribute to it. You can add an icon with the data-icon attribute and optionally set its position with the data-iconpos attribute.

<a href="#" data-role="button" data-icon="star">Star button</a>
Star button 

Play with theme swatches

jQuery Mobile has a robust theme framework that supports up to 26 sets of toolbar, content and button colors, called a "swatch". Just add a data-theme="e" attribute to any of the widgets on this page: page, header, list, input for the slider, or button to turn it yellow. Try different swatch letters in default theme from a-e to mix and match swatches.
Cool party trick: add the theme swatch to the page and see how all the widgets inside the content will automatically inherit the theme (headers and footers don't inherit, they default to swatch "a").
<a href="#" data-role="button" data-icon="star" data-theme="a">Button</a>data-theme="a" data-theme="b" data-theme="c" data-theme="d" data-theme="e" 
When you're ready to build a custom theme, use ThemeRoller to drag and drop, then download a custom theme.


button models


<a href="#" data-role="button" data-icon="star">Star button</a>

<a href="#" data-role="button" data-icon="star">Star button</a>
<a href="#" data-role="button" data-icon="home">home button</a>
<a href="#" data-role="button" data-icon="delete">delete button</a>
<a href="#" data-role="button" data-icon="plus">plus button</a>
<a href="#" data-role="button" data-icon="arrow-u">up arrow button</a>
<a href="#" data-role="button" data-icon="arrow-d">down arrow button</a>
<a href="#" data-role="button" data-icon="arrow-r">right arrow button</a>
<a href="#" data-role="button" data-icon="arrow-l">left arrow button</a>
<a href="#" data-role="button" data-icon="check">check button</a>
<a href="#" data-role="button" data-icon="gear">gear button</a>
<a href="#" data-role="button" data-icon="grid">grid button</a>
<a href="#" data-role="button" data-icon="custom">custom button</a>
<a href="#" data-role="button" data-icon="minus">minus button</a>
<a href="#" data-role="button" data-icon="plus">plus button</a>
<a href="#" data-role="button" data-icon="refresh">refresh button</a>
<a href="#" data-role="button" data-icon="forward">forward button</a>
<a href="#" data-role="button" data-icon="back">back button</a>
<a href="#" data-role="button" data-icon="alert">alert button</a>
<a href="#" data-role="button" data-icon="info">info button</a>
<a href="#" data-role="button" data-icon="search">search button</a>

JSON Datatable Pagination with wcf service


interface of wcf service

IService.cs

  [OperationContract]
             [WebInvoke(UriTemplate = "/SAVEMYLIST", Method = "POST",
             RequestFormat = WebMessageFormat.Json,
             ResponseFormat = WebMessageFormat.Json)]
             int GETDBD_SAVEMYLIST(List<DPSLIST> liDPS);

             [OperationContract]
             [WebGet(UriTemplate = "/GETmylist/{userStr}",-- this is the flexible name to gave it into user
                ResponseFormat = WebMessageFormat.Json)]
             List<SrchPrefer> GETMyUserList(string userStr);




myservice.svc


 public int GETDBD_SAVEMYUSERLIST(List<MyUser> liMyUser)
        {
            con.ConnectionString = sConnStr;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SAVE_MYUsers";
            cmd.CommandType = CommandType.StoredProcedure;
            string prepXML =//convert list to xml here the you got the xml
         
            cmd.Parameters.AddWithValue("@SAVEXML", prepXML);
            cmd.Parameters.AddWithValue("@Finialize", "");
            cmd.ExecuteNonQuery();

            return 1;
        }

        public List<Myuser> GETDBD_GETPREFERENCES(string userStr)
        {
            List<Myuser> liMyuser = new List<Myuser>();
            try
            {
//                databse calling
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    foreach (DataRow dr in dt.Rows)
                    {
                        liMyuser.Add(new Myuser()
                        {
                            username = Convert.ToString(dr["username"].ToString()),
                            usercode = Convert.ToString(dr["usercode"].ToString()),                      

                            ID = Convert.ToString(dr["ID"].ToString()),

                            DEVSTATUS = "U"

                            // USERCODE = Convert.ToString(dr["USERCODE"].ToString()),
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
            return liMyuser;
        }

service configerations file web.config


<?xml version="1.0"?>
<configuration>
  <appSettings>
 
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
       
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="webby">
       
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="secure">
          <security mode="Transport">
            <transport clientCredentialType="Basic"/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="GTKDPSWService.GTKDPS">
        <endpoint address="bh" binding="basicHttpBinding" contract="MyWService.IService" />
        <endpoint address="wh" binding="wsHttpBinding"  contract="MyWService.IService" />
        <endpoint address="json" behaviorConfiguration="webby" binding="webHttpBinding"
                  contract="MyWService.IService"/>
        <endpoint contract="MyWService.IService" binding="mexHttpBinding" address="mex" />
        <endpoint address="jh" binding="wsHttpBinding"  bindingConfiguration="NoSecurity"
                  contract="MyWService.IService" />
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>





</configuration>




Mypage2.aspx

 function BindScreeningList(_json) {

            var datagrid = $("#divdatagridDtls");
            datagrid.html('<table cellpadding="0" cellspacing="0" border="0" class="ui-table" style="width:100%" id="tbScreenDtls"></table>');

            $('#tbScreenDtls').dataTable({
                "bSort": false,
                "bProcessing": true,
                "aaData": _json,
                "aoColumnDefs": [
                            { "sWidth": "2%", "mData": "LISTID",
                                "mRender": function (data, type, row) {
                                    if (row.ISACTIVE == 'Y') {
                                        selectedids.push([row.LISTID]);
                                        return '<input type="checkbox" checked="checked" class="regular-checkbox" id="checkbox-' + row.LISTID + '" onclick="selectid(this,' + row.LISTID + ')"; /><label for="checkbox-' + row.LISTID + '"></label>';
                                    }
                                    else {
                                        return '<input type="checkbox" class="regular-checkbox" id="checkbox-' + row.LISTID + '" onclick="selectid(this,' + row.LISTID + ')"; /><label for="checkbox-' + row.LISTID + '"></label>';
                                    }
                                }, "aTargets": [0]
                            },
                            { "sTitle": "List ID", "mDataProp": "LISTID", "sWidth": "5%", "aTargets": [1] },
                            { "sTitle": "List Code", "mDataProp": "LISTCD", "sWidth": "5%", "aTargets": [2] },
                            { "sTitle": "Country", "mDataProp": "CNTY", "sWidth": "5%", "aTargets": [3] },
                            { "sTitle": "List Name", "mDataProp": "LISTNAME", "sWidth": "55%", "aTargets": [4] },
                            { "sTitle": "List SRC", "mDataProp": "LISTSRC", "sWidth": "10%", "aTargets": [5] },
                            { "sTitle": "Category", "mDataProp": "LISTCATEGORY", "sWidth": "10%", "aTargets": [6] }
                        ],
                "bJQueryUI": true,
                "sPaginationType": "full_numbers"
            });

        }




function DPSSave(_json) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(_json),
            url: ServiceURL + "SAVEMYSRCLIST",
            success: function (data) {
                alert('List Saved Succesfully.');

            }
        });
    }
        $(document).on("click", "#CancelKey", function () {
            getSearch();

        });

 <div id="divdatagridDtls" style="padding-left: 5%;padding-right: 5%;">



mypage.aspx


 <script type="text/javascript">
        $(document).ready(function () {

            var randomh = Math.random();
            //loadgenericcssandjsfiles();          
            loadjscssfile('../../../Styles/CSS/jquery.mobile-1.2.0.min.css?x=' + randomh, 'css', function () { return true; });
     
            getSearch();
        });


        function getSearch() {

            $.ajax({

                type: "GET",

                url: ServiceURL + "RECENTSRCH",

                data: "{}",

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success: function (response) {
                    var jsonPieObj1 = response;
                    bindRecentSrch(jsonPieObj1);
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }

        // grid options
        var options = {
            columns: [
                                { label: "", field: "RESULT",
                                    rendererFunction: function (cell, columnData) {
                                     
                                        if (columnData.data == 'YES')
                                            $('<span class="greendot" />').appendTo(cell);
                                        else
                                            $('<span class="reddot" />').appendTo(cell);
                                    }
                                },
                                { label: "Name", field: "PARTNER" },
                                { label: "Country", field: "COUNTRYSRCH" },
                                 { label: "User", field: "USER" },
                                { label: "Date", field: "DATE" }
                     ],
            rowFunction: function (tr, rowIndex, rowData) {
                if (rowIndex % 2 == 0)
                    $(tr).addClass('blu');
                else
                    $(tr).addClass('alt');
            }
        };

        function bindRecentSrch(jsonPieObj1) {
            var datagrid = $("#datagrid");
            datagrid.grid(options);
            datagrid.grid("option", "dataProvider", jsonPieObj1);
            datagrid.find('table').addClass('ui-table');
            var vth = $('#datagrid').find('th');
            var i = 0;
            $(vth).each(function () {
                if (i == 0) $(this).css('width', '2%');
                if (i == 1) $(this).css('width', '88%');
                if (i == 2) $(this).css('width', '3%');
                if (i == 3) $(this).css('width', '3%');
                i++;

            });


        }
       
    </script>



Pagination.js


//For avoiding "No- Transport" error
//force cross-site scripting (as of jQuery 1.5)
jQuery.support.cors = true;


var sPagingParameter = { "iDisplayStart": "", "iDisplayLength": "", "sSearch": "", "bEscapeRegex": "", "iColumns": "",
    "iSortingCols": "", "iSortCol_0": "", "sSortDir_0": "", "sEcho": "", "websiteId": "", "categoryId": "", "iTotalRecords": "",
    "iTotalDisplayRecords": "",
    "aaData": [],
    "fpData":[]
};

var idTable;
var oCache = {
    iCacheLower: -1
};

function fnSetKey(aoData, sKey, mValue) {
    for (var i = 0, iLen = aoData.length; i < iLen; i++) {
        if (aoData[i].name == sKey) {
            aoData[i].value = mValue;
        }
    }
}

function fnGetKey(aoData, sKey) {
    for (var i = 0, iLen = aoData.length; i < iLen; i++) {
        if (aoData[i].name == sKey) {
            return aoData[i].value;
        }
    }
    return null;
}

function fnDataTablesPipeline(sSource, aoData, fnCallback, jsonarray) {

 

    var iPipe = 5; /* Ajust the pipe size */

    var bNeedServer = false;
    var sEcho = fnGetKey(aoData, "sEcho");
    var iRequestStart = fnGetKey(aoData, "iDisplayStart");
    var iRequestLength = fnGetKey(aoData, "iDisplayLength");
    var iRequestEnd = iRequestStart + iRequestLength;
    oCache.iDisplayStart = iRequestStart;

    /* outside pipeline? */
    if (oCache.iCacheLower < 0 || iRequestStart < oCache.iCacheLower || iRequestEnd > oCache.iCacheUpper) {
        bNeedServer = true;
    }

    /* sorting etc changed? */
    if (oCache.lastRequest && !bNeedServer) {
        for (var i = 0, iLen = aoData.length; i < iLen; i++) {
            if (aoData[i].name != "iDisplayStart" && aoData[i].name != "iDisplayLength" && aoData[i].name != "sEcho") {
                if (aoData[i].value != oCache.lastRequest[i].value) {
                    bNeedServer = true;
                    break;
                }
            }
        }
    }

    /* Store the request for checking next time around */
    oCache.lastRequest = aoData.slice();

    if (bNeedServer) {
        if (iRequestStart < oCache.iCacheLower) {
            iRequestStart = iRequestStart - (iRequestLength * (iPipe - 1));
            if (iRequestStart < 0) {
                iRequestStart = 0;
            }
        }

        oCache.iCacheLower = iRequestStart;
        oCache.iCacheUpper = iRequestStart + (iRequestLength * iPipe);
        oCache.iDisplayLength = fnGetKey(aoData, "iDisplayLength");
        fnSetKey(aoData, "iDisplayStart", iRequestStart);
        fnSetKey(aoData, "iDisplayLength", iRequestLength * iPipe);


        var aoHash = {};
        $.each(aoData, function () {
            var item = this;
            aoHash[item.name] = item.value;
        });

        $.ajax({
            "dataType": 'json',
            "contentType": "application/json",
            "type": "POST",
            "url": sSource,
            "data": JSON.stringify(aoHash),
            "success": function (msg) {
                tmpJsonArray = msg;
                //                            var jsond = eval(msg);
                var jsond = JSON.stringify(msg);
                var b = jQuery.parseJSON(jsond);

                oCache.lastJson = jQuery.extend(true, {}, b);
                if (oCache.iCacheLower != oCache.iDisplayStart) {
                    b.aaData.splice(0, oCache.iDisplayStart - oCache.iCacheLower);
                }
                b.aaData.splice(oCache.iDisplayLength, b.aaData.length);

                fnCallback(b);

                return true;
            },
            "error": function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.responseText);

            }
        });
    }
    else {
        json = jQuery.extend(true, {}, oCache.lastJson);
        json.sEcho = sEcho; /* Update the echo for each response */
        json.aaData.splice(0, iRequestStart - oCache.iCacheLower);
        json.aaData.splice(iRequestLength, json.aaData.length);
        fnCallback(json);
        return;
    }
}


var tmpJsonArray = [];
var aParams = [];
var fpData = [];

var oTable;
function GridWCFServiceCall(uriTemplate, aoColumnDefs, controlId) {
    $('#' + controlId).dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "bJQueryUI": true,
        "bAutoWidth": true,
        "bSort": false,
        "sAjaxSource": ServiceURL + uriTemplate,
        "sPaginationType": "full_numbers",
        "sAjaxDataProp": "aaData",
        "sServerMethod": "POST",
        "fnServerData": function (sSource, aoData, fnCallback, oSettings) {

            //            if (aParams.length > 0) {
            //                $.each(aParams, function () {
            //                    var item = this;
            //                    aoData.push({ "name": item.name, "value": item.value });
            //                });
            //            }


            var aoHash = {};
            $.each(aoData, function () {
                var item = this;
                aoHash[item.name] = item.value;
            });

            aoHash["aoParams"] = JSON.stringify(aParams);
           // aoHash["fpData"] = JSON.stringify(fpData);

            aoHash["stData"] = JSON.stringify(fpData);
            //document.write(JSON.stringify(aoHash));

            oSettings.jqXHR = $.ajax({
                "dataType": 'json',
                "contentType": "application/json",
                "type": "POST",
                "url": sSource,
                "data": JSON.stringify(aoHash),
                "success": function (msg) {
                    tmpJsonArray = msg;
                    // var jsond = eval(msg);
                    var jsond = JSON.stringify(msg);
                    var b = jQuery.parseJSON(jsond);

                    fnCallback(b);

                    return true;
                },
                "error": function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                    alert(XMLHttpRequest.status);
                    alert(XMLHttpRequest.responseText);

                }
            });
        },
        "aoColumnDefs": aoColumnDefs,
        "fnDrawCallback": function (oSettings) {
            onCallSuccess(controlId);
        }

    });
}



function GridWCFServiceCallPipeLine(uriTemplate, aoColumnDefs, controlId) {
 
    $('#' + controlId).dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "bJQueryUI": true,
        "bAutoWidth": true,
        "bSort": false,
        "sAjaxSource": ServiceURL + uriTemplate,
        "sPaginationType": "full_numbers",
        "sAjaxDataProp": "aaData",
        "fnServerData": fnDataTablesPipeline,
        "aoColumnDefs": aoColumnDefs
    });
}




datatable download: http://datatables.net/download/

JSON vs. Arrays


What is JSON

  • JSON = JavaScript Object Notation
  • Object that contains Data
  • Better than XML for use with Javascript (cause it is not a markup language and it is lightweight)
  • Easier and quicker to setup than XML on the server-side

JSON vs. Arrays

  • JSON wins
  • Not a good comparison since JSON can have arrays inside of it
  • JSON can store nested objects and arrays, it is much more powerful than an array

What does JSON look like?

Declaring an empty JSON object in Javascript:
var data = {};
A basic JSON object:
var data = {kind: "Human", water: "Clear Blue", help: false};
A complex JSON object:
var bar = {prop: [{key: "Value", x: "yes"},{alien: false, skin: "Green Tone"}], sand:true};
var data = {kind: "Human", water: "Clear Blue", help: false, extra: bar};

How do I set it up a JSON in PHP?

A simple example that outputs a static JSON object:
<?
header("Content-type: application/json");
echo '{"items: [ key: "value", another_key: { k: "val", x: "yes" } ]}';
?>
Convert PHP arrays into JSON:
<?
header("Content-type: application/json");
$my_object '{"items: [ key: "value", another_key: { k: "val", x: "yes" } ]}';
$count = 2;
echo json_encode(array("items" => $my_object"count" => $count));
?>
Get data from a database and turn it into JSON with PHP:
<?
$input $_GET["q"];
$data array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Using JSON with jQuery

Query the server and alert some JSON data:
$.getJSON("http://mysite.com/path/to/script"function(data){
var items = data.items[0];
alert(items.key);
});