http://www.imomin.webs.com

Thank You for Visit Me

Md. Mominul Islam

view:  full / summary

JQuery Flot Charts with Time Series

Posted by Komol on August 18, 2011 at 5:50 AM Comments comments (0)

Flot is an awesome library to produce the simple charts based on the great JQuery.

Using the date/time data (e.g. X-axis data type) is a little difficult to get working right but after exchanging the emails with the developer of the Flot library, I got it right and this solution I couldn’t find anywhere on Google/Bing.

Here’s the code snippet and I hope this helps.

This example uses our OLD json-based asmx ASP.Net service (sorry, I didn’t need to use WCF). :) You may have to tweak this code to suite your needs.

 


   1:  function LoadCharts() {

 

   2:      $.ajax({

 

   3:          type: "POST",

 

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

 

   5:          url: "SomeService.asmx/ChartData",

 

   6:          data: "{dataFor: 'blah'}",

 

   7:          success:

 

   8:      function(msg) {

 

   9:          ProcessCharts($.evalJSON(msg).d);

 

  10:      },

 

  11:          error:

 

  12:      function(XMLHttpRequest, textStatus, errorThrown) {        

 

  13:          alert(XMLHttpRequest.responseText);

 

  14:      }

 

  15:      });

 

  16:  }

 

  17:   

 

  18:  function ProcessCharts(tables) {

 

  19:      var plot0, plot1, plot2;

 

  20:      //Assume I've 3 tables in the result.

 

  21:      $(tables).each(function(i) {

 

  22:          var data = tables[i].Data;

 

  23:          var plotData = [];

 

  24:          var offset = new Date().getTimezoneOffset() * 60 * 1000;

 

  25:          

 

  26:      //TODO: find a simple better way in jquery to do this.

 

  27:          for (var j = 0; j < data.length; j++) {

 

  28:              var d = data[j].Date; //my case the date is 20090101 format

 

  29:              d = d.substr(4, 2) + "/" + d.substr(6, 2) + "/" + d.substr(0, 4);

 

  30:              var date = new Date(d).getTime() - offset;

 

  31:              tables[i].Data[j].Date = date;

 

  32:   

 

  33:              plotData.push([date, data[j].Val]);

 

  34:          }

 

  35:          var previousPoint = null;

 

  36:          var lbl = "";

 

  37:          var options = {

 

  38:              colors: ['#123658', '#000000'],

 

  39:              series: {

 

  40:                  lines: { show: true, lineWidth: 2 },

 

  41:                  points: {

 

  42:                      show: true

 

  43:                  }

 

  44:              },

 

  45:              shadowSize: 5,

 

  46:              grid: {

 

  47:                  hoverable: true,

 

  48:                  clickable: false,

 

  49:                  borderWidth: 1,

 

  50:                  backgroundColor: '#ddf0ff'

 

  51:              },

 

  52:              legend: {

 

  53:                  show: false

 

  54:                  //"nw"

 

  55:              },

 

  56:              xaxis: {

 

  57:                  mode: "time",

 

  58:                  timeformat: "%m/%d/%y",

 

  59:                  minTickSize: [1, "day"]

 

  60:              }

 

  61:          };

 

  62:          var InitChart = function() {

 

  63:   

 

  64:              $("#Chart" + i).remove();

 

  65:   

 

  66:              return $.plot($("#Chart" + i),

 

  67:              [{ data: plotData, label: lbl }],

 

  68:              options

 

  69:              );

 

  70:          }

 

  71:      //I've more tables in my case so change this code as per your need

 

  72:          switch (i.toString()) {

 

  73:              case "0":

 

  74:                  lbl = "Label1";

 

  75:                  plot0 = InitChart();

 

  76:                  break;

 

  77:              default:

 

  78:                  break;

 

  79:          }

 

  80:   

 

  81:          $("#Chart" + i).bind("plothover", function(event, pos, item) {

 

  82:              if (item) {

 

  83:                  if (previousPoint != item.datapoint) {

 

  84:                      previousPoint = item.datapoint;

 

  85:   

 

  86:                      $("#tooltip").remove();

 

  87:                      var x = item.datapoint[0], y = item.datapoint[1];

 

  88:   

 

  89:                      var d = new Date();

 

  90:                      d.setTime(x + offset);

 

  91:   

 

  92:                      showTooltip(item.pageX, item.pageY, "Total " + item.series.label + " of " + d.toDateString() + " is " + addCommas(y));

 

  93:                  }

 

  94:              }

 

  95:              else {

 

  96:                  $("#tooltip").remove();

 

  97:                  previousPoint = null;

 

  98:              }

 

  99:          });

 

 100:      });

 

 101:   

 

 102:  }

 

 103:   

 

 104:  function showTooltip(x, y, contents) {

 

 105:      $('<div id="tooltip">' + contents + '</div>').css({

 

 106:          'absolute',

 

 107:          display: 'block',

 

 108:          "z-index": 10,

 

 109:          top: y + 5,

 

 110:          left: x + 5,

 

 111:          border: '1px solid #e17009',

 

 112:          padding: '3px',

 

 113:          'background-color': '#fee',

 

 114:          opacity: 0.70,

 

 115:          margin: '5px',

 

 116:          'font-size': '10px'

 

 117:      }).appendTo("body").fadeIn(200);

 

 118:  }

 

 


How do you setup a linked server to an Oracle database on SQL

Posted by imomins on July 26, 2011 at 8:05 AM Comments comments (0)

setup a linked server to a remote Oracle database, which ended up being a multi-step process:

Install Oracle ODBC drivers on SQL Server.

Create System DSN to Oracle database on SQL Server.

Create linked server on SQL server using System DSN.

Step 1: Install Oracle ODBC drivers on server

a. Download the necessary Oracle Instant Client packages: Basic, ODBC, and SQL*Plus (optional)

b. Unzip the packages to a local directory on the SQL server, typically C:\Oracle. This should result in a [directory] like *C:\Oracle\instantclient_10_2*, which will be the value of [directory] referenced in the rest of this answer.

c. Create a text file named tnsnames.ora within the instant client [directory] that contains the following:

OracleTnsName =

(

  DESCRIPTION=

  (

    ADDRESS = (PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521)

  )

  (

    CONNECT_DATA = (SERVICE_NAME=acc)

  )

)

Note: Actual HOST, PORT, and SERVICE_NAME will vary based on Oracle server you are establishing a connection to. This information can often be found using the Oracle network client tools under the listeners.

The OracleTnsName can be any name you want to assign to the Oracle data source, and will be used when setting up the system DSN. You can also use the syntax above to define multiple TNS names in the same tnsnames.ora file if desired.

d. Add the [directory] to the system PATH environment variable.

e. Create a new system environment variable named TNS_Admin that has a value of [directory]

f. Execute the [directory]**odbc_install.exe** utility to install the Oracle ODBC drivers.

 

g. It is recommended that you reboot the SQL server, but may not be necessary. Also, you may want to grant security permissions to this directory for the SQL server and SQL agent user identities.


Step 2: Create a System DNS that uses the Oracle ODBC driver

a. Open the ODBC Data Source Administrator tool. [ Administrative Tools --> Data Sources (ODBC) ]

b. Select the System DSN tab and then select the Add button.

c. In the drivers list, select Oracle in instantclient {version}. (e.g. 'Oracle in instantclient 10_2') and then select Finish button.

d. Specify the following:

 

Data Source Name: {System DSN Name}

Description: {leave blank/empty}

TNS Service Name: should have the OracleTnsName you defined in the tnsnames.ora file listed, select it as the value.

User ID: {Oracle user name}


e. Select Test Connection button. You should be prompted to provide the {Oracle user password}. If all goes well the test will succeed.


Step 3: Create linked server in SQL to the Oracle database

Open a query window in SQL server and execute the following:

EXEC sp_addlinkedserver

     @server            = '{Linked Server Name}'

    ,@srvproduct        = '{System DSN Name}'

    ,@provider          = 'MSDASQL'

    ,@datasrc           = '{System DSN Name}'

 

EXEC sp_addlinkedsrvlogin

     @rmtsrvname        = '{Linked Server Name}'

    ,@useself           = 'False'

    ,@locallogin        = NULL

    ,@rmtuser           = '{Oracle User Name}'

    ,@rmtpassword       = '{Oracle User Password}'

Note: The {Linked Server Name} can be anything you want to use when referencing the Oracle server, but the {System DNS Name} must match the name of the system DSN you created previously.

The {Oracle User Name} should be the same as the User ID used by the system DSN, and the {Oracle User Password} should be the same as you used to sucessfully test the ODBC connection. See KB 280106 for information on troubleshooting Oracle linked server issues.

Querying the Oracle linked server

You may use OPENQUERY to execute pass-through queries on the Oracle linked server, but be aware that for very large recordsets you may recieve a ORA-01652 error message if you specify a ORDER BY clause in the pass-through query. Moving the ORDER BY clause from the pass-through query to the outer select statement solved this issue for me.

 


 

 


 

 

Topic: Install and Setup Guide for Extjs Visual Studio

Posted by imomins on July 12, 2011 at 11:10 AM Comments comments (0)

Hi everyone. I have been spending the day working with Ext.Net and so far I am loving it. I have been looking for something like this for over a year now and am excited to get started with it.

I wanted to give back by sharing my experience with setting up and installing Ext.Net with Visual Studios. I had noticed that there weren’t really any step by step instructions for people who are new to .Net and thought I would try to help out by adding this guide on how to start using Ext.Net within your project. Hopefully this will help out someone if they are get getting started with ASP.Net

This is the setup I used for installing and setting up Ext.Net within Visual Studios 2010. I have tested it with the .net 4.0 framework and have not had any problems.

To start you will need to download the latest version.Unzip the contents of the zip file into a new directory.Open the directory and copy the following files to your projects /bin directory:Ext.Net.dllExt.Net.Utilities.dllExt.Net.xmlNewtonsoft.Json.dllNewtonsoft.Json.xmlIn the solution explorer make sure the view all files button is selected.Expand the /bin directory to display all files and Click the refresh button at the topselect each of the new files you just added to the /bin directory (shift + click)Right click and choose “Include in Project”Add references to Ext.Net

In solution Explorer Click the properties button for your project (top left button).Click on References tab on the left. You should see all references in the center.Click the Add button and then the browse tab.Browse to your projects /bin directory (were you copied the DLL’s to) and select the 3 DLL’s and click ok.Under Imported namespaces scroll to the bottom and click on the checkboxes for the following:

*Note: Include which ever ones you plan to use.12345ExtExt.NetExt.Net.UtilitiesNewtonsoftNewtonsoft.JsonSave your project.Web.config changes

Open your web.config file. You will need to add the following to your config file.Find:

12<configuration> <configSections>Add:

1<section name="extnet" type="Ext.Net.GlobalConfig" requirePermission="false" />

Add Ext.Net to your toolbox.

Open a .aspx file to exit in visual studios. We do this so items are displayed within your toolbox (if its a .vb, .cs, etc it will not display items).Next click on your toolbar and click add tab. Name this tab something (Ext.Net)Right click under this tab click choose itemsClick the Browse button under “.NET Framework Components”If no errors are displayed you should now see all the components under the new tab.I suggest going though and creating several new tabs to help sort and group the 100+ controls that are now added. Ext.net Forms, Ext.net Data, Ext.net Design are some examples I use.

Testing within your project:

Before you begin I would suggest doing a Build Clean and Rebuild to confirm all the new changes are set.

To use Ext.Net within your page requires 2 changes to an existing page. A register tag and the resourcemanager tag.

Open a file within your project (or create a new file – right click project name > add > New item).At the top of your page (under the page directive) add:1<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>This will give you access to the Ext.Net DLL

Save your .aspx file, build and run the page (ctrl + F5)You should now see the control displayed on the page. If it is not installed there was a problem somewhere with your install. You should see some type of error directing you on how to solve the problem.Problems, errors and issues:

Here are some common problems you may run into and how to solve the problems.

Question: Ext.Net tools are not displayed in the toolbar?

Answer: Make sure you are editing a .aspx file. If other tools are displayed but not Ext.Net then you may not have added the dll correctly.

Question: The ResourceManager Control is missing from this Page.

Answer: You did not add the ResourceManager to your page. Add the following tag UNDER your <body> tag: <ext:ResourceManager ID=”ResourceManager1″ runat=”server” />

Question: Parser Error Message: Unknown server tag ‘ext:ResourceManager’.

Answer: Add the following under your page directive (under the <@Page tag):

http://chuotit.com/2011/06/install-and-setup-guide-for-visual-studio/

 

jQuery.ajax( url, [settings] )

Posted by imomins on July 11, 2011 at 11:02 AM Comments comments (0)

jQuery.ajax( url, [settings] )urlA string containing the URL to which the request is sent.

settingsA set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.

version added: 1.0jQuery.ajax( settings )settingsA set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().

acceptsMapDefault: depends on DataTypeThe content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method

asyncBooleanDefault: trueBy default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

beforeSend(jqXHR, settings)FunctionA pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings maps are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

cacheBooleanDefault: true, false for dataType 'script' and 'jsonp'If set to false, it will force requested pages not to be cached by the browser.

complete(jqXHR, textStatus)Function, ArrayA function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

contents(added 1.5)MapA map of string/regular-expression pairs that determine how jQuery will parse the response, given its content type.

contentTypeStringDefault: 'application/x-www-form-urlencoded'When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.

contextObjectThis object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

$.ajax({

url: "test.html",

context: document.body,

success: function(){

$(this).addClass("done");

}

});converters(added 1.5)MapDefault: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response

crossDomain(added 1.5)Default: false for same-domain requests, true for cross-domain requestsIf you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain

dataObject, StringData to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

dataFilter(data, type)FunctionA function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.

dataTypeStringDefault: Intelligent Guess (xml, json, script, or html)The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery."html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM."script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests."json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. "text": A plain text string.multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml. error(jqXHR, textStatus, errorThrown)FunctionA function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

globalBooleanDefault: trueWhether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.

headers(added 1.5)MapDefault: {}A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

ifModifiedBooleanDefault: falseAllow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.

isLocal(added 1.5.1)BooleanDefault: depends on current location protocolAllow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method.

jsonpStringOverride the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }

jsonpCallbackString, FunctionSpecify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

mimeType(added 1.5.1)StringA mime type to override the XHR mime type.

passwordStringA password to be used in response to an HTTP access authentication request.

processDataBooleanDefault: trueBy default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

scriptCharsetStringOnly for requests with "jsonp" or "script" dataType and "GET" type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

statusCode(added 1.5)MapDefault: {}

A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({

statusCode: {

404: function() {

alert('page not found');

}

}

}); If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.

success(data, textStatus, jqXHR)Function, ArrayA function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

timeoutNumberSet a local timeout (in milliseconds) for the request. This will override the global timeout, if one is set with $.ajaxSetup(). For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See $.ajaxSetup() for global timeouts. In jQuery 1.4.x and below, please note that the XMLHttpRequest object will be in an invalid state should the request time out. Where this is the case, accessing any object members may result in an exception being thrown. In jQuery 1.5.2 and above,$.ajax() does not handle JSONP requests as expected should the request fail due to a timeout in Firefox 3.0+. This is a browser-based issue due to FF currently not providing a way to abort cross-domain requests once the script tag has been appended. This issue does not currently affect other browsers.

traditionalBooleanSet this to true if you wish to use the traditional style of param serialization.

typeStringDefault: 'GET'The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

urlStringDefault: The current page A string containing the URL to which the request is sent.

usernameStringA username to be used in response to an HTTP access authentication request.

xhrFunctionDefault: ActiveXObject when available (IE), the XMLHttpRequest otherwiseCallback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

xhrFields(added 1.5.1)MapA map of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

$.ajax({

url: a_cross_domain_url,

xhrFields: {

withCredentials: true

}

});In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.

The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.

At its simplest, the $.ajax() function can be called with no arguments:

$.ajax();Note: Default settings can be set globally by using the $.ajaxSetup() function.

This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, we can implement one of the callback functions.

The jqXHR ObjectThe jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:

$.ajax({

url: 'http://fiddle.jshell.net/favicon.png',

beforeSend: function( xhr ) {

xhr.overrideMimeType( 'text/plain; charset=x-user-defined' );

},

success: function( data ) {

if (console && console.log){

console.log( 'Sample of data:', data.slice(0,100) );

}

}

});

The jqXHR objects returned by $.ajax() implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). For convenience and consistency with the callback names used by $.ajax(), jqXHR also provides .error(), .success(), and .complete() methods. These methods take a function argument that is called when the $.ajax() request terminates, and the function receives the same arguments as the correspondingly-named $.ajax() callback. In jQuery 1.5 this allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.)

// Assign handlers immediately after making the request,

// and remember the jqxhr object for this request

var jqxhr = $.ajax({ url: "example.php" })

.success(function() { alert("success"); })

.error(function() { alert("error"); })

.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above

jqxhr.complete(function(){ alert("second complete"); });For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

readyStatestatusstatusTextresponseXML and/or responseText when the underlying request responded with xml and/or text, respectivelysetRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old onegetAllResponseHeaders()getResponseHeader()abort()No onreadystatechange mechanism is provided, however, since success, error, complete and statusCode cover all conceivable requirements.

Callback Function QueuesThe beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.

As of jQuery 1.5, the error, success, and complete callback hooks are first-in, first-out managed queues. This means you can assign more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax() callback hooks.

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

Some types of Ajax requests, such as JSONP and cross-domain GET requests, do not use XHR; in those cases the XMLHttpRequest and textStatus parameters passed to the callback are undefined.

Here are the callback hooks provided by $.ajax():

beforeSend callback is invoked; it receives the jqXHR object and the settings map as parameters.error callbacks are invoked, in the order they are registered, if the request fails. They receive the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".dataFilter callback is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success.success callbacks are then invoked, in the order they are registered, if the request succeeds. They receive the returned data, a string containing the success code, and the jqXHR object.complete callbacks fire, in the order they are registered, when the request finishes, whether in failure or success. They receive the jqXHR object, as well as a string containing the success or error code.For example, to make use of the returned HTML, we can implement a success handler:

$.ajax({

url: 'ajax/test.html',

success: function(data) {

$('.result').html(data);

alert('Load was performed.');

}

});Data TypesThe $.ajax() function relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected, such as HTML in the example above, the data is treated as text.

Different data handling can be achieved by using the dataType option. Besides plain xml, the dataType can be html, json, jsonp, script, or text.

The text and xml types return the data with no processing. The data is simply passed on to the success handler, either through the responseText or responseXML property of the jqXHR object, respectively.

Note: We must ensure that the MIME type reported by the web server matches our choice of dataType. In particular, XML must be declared by the server as text/xml or application/xml for consistent results.

If html is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, script will execute the JavaScript that is pulled back from the server, then return nothing.

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor. Malformed JSON data will throw a parse error (see json.org for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the jsonp type instead.

The jsonp type appends a query string parameter of callback=? to the URL. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than callback with the jsonp option to $.ajax().

Note: JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. More information about it can be found in the original post detailing its use.

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.

Sending Data to the ServerBy default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

Advanced OptionsThe global option prevents handlers registered using .ajaxSend(), .ajaxError(), and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend() if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false. See the descriptions of these methods below for more details. See the descriptions of these methods below for more details.

If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.

Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.

By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false. To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true.

The scriptCharset allows the character set to be explicitly specified for requests that use a <script> tag (that is, a type of script or jsonp). This is useful if the script and host page have differing character sets.

The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort() on the object will halt the request before it completes.

Extending AjaxAs of jQuery 1.5, jQuery's Ajax implementation includes prefilters, converters, and transports that allow you to extend Ajax with a great deal of flexibility. For more information about these advanced features, see the Extending Ajax page.

Additional Notes:Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.Script and JSONP requests are not subject to the same origin policy restrictions.Examples:Example: Load and execute a JavaScript file.$.ajax({

   type: "GET",

   url: "test.js",

   dataType: "script"

 });Example: Save some data to the server and notify the user once it's complete.$.ajax({

   type: "POST",

   url: "some.php",

   data: "name=John&location=Boston",

   success: function(msg){

     alert( "Data Saved: " + msg );

   }

 });Example: Retrieve the latest version of an HTML page.$.ajax({

  url: "test.html",

  cache: false,

  success: function(html){

    $("#results").append(html);

  }

});Example: Loads data synchronously. Blocks the browser while the requests is active.It is better to block user interaction by other means when synchronization isnecessary.var html = $.ajax({

  url: "some.php",

  async: false

 }).responseText;Example: Sends an xml document as data to the server. By setting the processDataoption to false, the automatic conversion of data to strings is prevented.var xmlDocument = [create xml document];

 $.ajax({

   url: "page.php",

   processData: false,

   data: xmlDocument,

   success: handleResponse

 });

Example: Sends an id as data to the server, save some data to the server and notify the user once it's complete. Note that this usage - returning the result of the call into a variable - requires a synchronous (blocking) request! (async:false)bodyContent = $.ajax({

      url: "script.php",

      global: false,

      type: "POST",

      data: ({id : this.getAttribute('id')}),

      dataType: "html",

      async:false,

      success: function(msg){

         alert(msg);

      }

   }

).responseText;


Jgrid

Posted by imomins on July 11, 2011 at 7:42 AM Comments comments (0)

jsonReader as FunctionIn certain situation you will obtain the data from a web service. In this case it is not possible to configure all the properties of the response so that the grid will work properly. As of version 3.6.4 it is possible to define the elements of the jsonReader as function. Below is a example on how this can be used:

jsonReader: {

repeatitems: false,

id: "Id",

root: function (obj) { return obj; },

page: function (obj) { return 1; },

total: function (obj) { return 1; },

records: function (obj) { return obj.length; }

}Where obj is the response from the service/server

Array DataDespite the fact that the primary goal of jqGrid is to represent dynamic data returned from a database, jqGrid includes a wide range of methods to manipulate data at client side: Array data.

Related options in options array: datataype

Related options in colModel: sorttype, datefmt

Related methods : getRowData, delRowData, setRowData, addRowData, updateGridRows See Methods

As of version 3.7 we introduce two additional parameters data and localReader. The data parameter is described in grid options.The localReader has the same sense as jsonReader described above, but applied to array data that is stored locally.

The initial configuration of the localReader is the same as those from jsonReader

localReader = {

root: "rows",

page: "page",

total: "total",

records: "records",

repeatitems: false,

cell: "cell",

id: "id",

userdata: "userdata",

subgrid: {root:"rows", repeatitems: true, cell:"cell"}

}All operations that are valid for jsonReader can be applied to localReader.

If we have defined a pager for grid with client side data, the buttons in pager are automatically disabled. In other words, the current release of grid does not support client side paging and serching.

First we must instruct jqGrid that the data that will be present is at client side. This is done with the option datatype. To use this we must set

jQuery("#grid_id").jqGrid({

...

datatype: "clientSide",

...

});The other option that can be used is “local” i.e. datatype: “local” These are the same.

Having this it is a good idea to set the sorttypes for the columns. If the sorttype is not set the default sorttype is “text”. Let's consider our example in terms of array data.

...

<script>

jQuery(document).ready(function(){

jQuery("#list").jqGrid({

datatype: 'clientSide',

colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],

colModel :[

{name:'invid',index:'invid', width:55, sorttype:'int'},

{name:'invdate',index:'invdate', width:90, sorttype:'date', datefmt:'Y-m-d'},

{name:'amount',index:'amount', width:80, align:'right',sorttype:'float'},

{name:'tax',index:'tax', width:80, align:'right',sorttype:'float'},

{name:'total',index:'total', width:80,align:'right',sorttype:'float'},

{name:'note',index:'note', width:150, sortable:false} ],

pager: '#pager',

rowNum:10,

viewrecords: true,

caption: 'My first grid'

});

...

});

</script>You can see the new setting here: datatype, sortype and datefmt.

The possible values for the sorttype are:

int - the data is interpreted as integer,

float - the data is interpreted as decimal number

date - the data is interpreted as date

text - the data is interpreted as text

We need this information for the appropriate sorting of these types. Additionally for the sorttype date we must known the format of the data that will be present in the grid. The default format is a ISO format 'Y-m-d'. The description of the date format is like a PHP way. For more information refer to php.net.

Let's add some data. This can be done with the method addRowData.

The parameters to this method are:

jQuery("#grid_id").addRowData( rowid, data, position, srcrowid );where:

rowid: this value will be set as the id of the row data: is the array of data in pair name:value, where the name is the name from colModel first” adds the new row at the top of the grid; “last” adds the data in the last position; “before” and “after” refer to the row identified in srcrowid. srcrowid: the id of a row which the new data is to be added either “before” or “after”<script>

...

var myfirstrow = {invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};

jQuery("#list").addRowData("1", myfirstrow);

...

</script>With this line we have added our first row. It is important to note that the order of the name-value pairs is arbitrary. Moreover, we can set a single name-value pair, like this.

<script>

...

jQuery("#list").addRowData("2", {amount:"300.00"});

...

</script>With this line we have added second row with only a value in the amount column.

To get data from the particular row we should use getRowData method:

jQuery("#grid_id").getRowData( rowid );where rowid is the id for the row which values we will obtain

jQuery("#list").getRowData( "1" );will return array of name-value pairs - the result is

{invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};To delete a row we should use delRowData method:

jQuery("#grid_id").delRowData( rowid );where rowid is the id of the row that can be deleted.

jQuery("#list").delRowData( "2" );will delete the row with the id = 2.

This method returns true if the deletion is successfully, false otherwise

To change all or part of the values in a given row, we can use a setRowData method.

jQuery("#grid_id").setRowData( rowid, data );whererowid is the id of the row which values will be changed

data is a array of data that contain the new values. The structure of array is in type name:value.

jQuery("#list").setRowData( "1", { tax:"5", total:"205" });will change the values tax and total of row with id = 1.

The method returns true if update is successful, otherwise false.

To update a set of grid rows at once we can use updateGridRows. For more info refer to Addon methods

FunctionThis option does not really define the datatype at all, but rather how to handle the data that is provided by the server (which would still come as either xml or json data). The functions defined as a Datatype should (or can) call addXMLData, addJSONData or addRowData once the data has been received.

Calling Convention:

datatype : function(postdata) {

// do something here

}Datatype functions are supplied with a single object containing the request information (parameter postdata), which normally would have been transformed into GET or POST arguments. This object is compatible with the data: option supplied to the jQuery $.ajax function.

Consider our example here is how this will work with datatype function:

<script type="text/javascript">

...

jQuery(document).ready(function(){

jQuery("#list").jqGrid({

datatype: function(postdata) {

jQuery.ajax({

url: 'example.php',

data:postdata,

dataType:"xml",

complete: function(xmldata,stat){

if(stat=="success") {

var thegrid = jQuery("#list")[0];

thegrid.addXmlData(xmldata.responseXML);

}

}

});

},

colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],

colModel :[

{name:'invid', index:'invid', width:55},

{name:'invdate', index:'invdate', width:90},

{name:'amount', index:'amount', width:80, align:'right'},

{name:'tax', index:'tax', width:80, align:'right'},

{name:'total', index:'total', width:80, align:'right'},

{name:'note', index:'note', width:150, sortable:false}

],

pager: '#pager',

rowNum:10,

rowList:[10,20,30],

sortname: 'invid',

sortorder: 'desc',

viewrecords: true,

caption: 'My first grid'

});

});

...

</script>User DataIn some cases we need to have custom data returned from the request that is not automatically displayed by jqGrid, that we use either in a later process or to display additional information somewhere in the HTML page or associated with the grid. To do that a userdata tag can be used.

In xmlReader this is defined as:

xmlReader: {

...

userdata: "userdata",

...

}This describes the tag where our custom data is. The important part here is that the XML tag should have a attribute name in order to associate data.

In the data received from the server, this could be structured as follows

<invoices>

<request>true</request>

<userdata name="totalinvoice"> 240.00 </userdata>

<userdata name="tax"> 40.00</userdata>

...

<result>

<row>

<cell>data1</cell>

<cell>data2</cell>

<cell>data3</cell>

<cell>data4</cell>

<cell>data5</cell>

<cell>data6</cell>

</row>

...

</result>

</invoices>If using json data, the definition might look like this:

jsonReader: {

...

userdata: "userdata",

...

}and the data received, like this:

{

total: "xxx",

page: "yyy",

records: "zzz",

userdata: {totalinvoice:240.00, tax:40.00},

rows : [

{id:"1", cell:["cell11", "cell12", "cell13"]},

{id:"2", cell:["cell21", "cell22", "cell23"]},

...

]

}When this data has been received, this information is stored in the userData array of the options array. Whichever format the data comes in, in this case we would have:

userData = {totalinvoice:240.00, tax:40.00}The data can be accessed two ways.

1. Using a getGridParam method. To do that we need to request this data:

jQuery("grid_id").getGridParam('userData')2. Using the user contributed Post Data Module

jQuery("grid_id").getUserData()to get the entry array or

jQuery("grid_id").getUserDataItem( key )to get particular value with name = key

 


২৯তম বিসিএসের ১৪৮০ জন নিয়োগ পেলেন(Download List)

Posted by imomins on July 11, 2011 at 7:25 AM Comments comments (0)

নিয়োগ পাওয়াদের তালিকা [Dowmload List]



২৯তম বিসিএস পরীক্ষায় চূড়ান্তভাবে উত্তীর্ণ ১ হাজার ৪৮০ জনকে নিয়োগ দিয়েছে সরকার।

জনপ্রশাসন মন্ত্রণালয়ের জ্যেষ্ঠ সহকারী সচিব মো. জাকির হোসেন রোববার স্বাক্ষরিত এক প্রজ্ঞাপনে নিয়োগের এ আদেশ দেওয়া হয়। সোমবার তা প্রকাশ হয়েছে।

নিয়োগ পাওয়াদের আগামী ১ অগাস্ট মন্ত্রণালয় নির্দেশিত কার্যালয়ে যোগ দিতে বলা হয়েছে।

এবার সবচেয়ে বেশি নিয়োগ দেওয়া হয়েছে শিক্ষা ক্যাডারে। এ ক্যাডারে নিয়োগ পেয়েছেন ৬৫৩ জন। শিক্ষার পরই রয়েছে কৃষিতে, এ ক্যাডারে ২০৪ জনকে নিয়োগ দেওয়া হয়েছে। স্বাস্থ্যে নিয়োগ পেয়েছেন ১৯৭ জন। প্রশাসন ক্যাডারে নিয়োগ দেওয়া হয়েছে ১৭৭ জনকে। পুলিশে নিয়োগ পেয়েছেন ৩৩ জন।

এছাড়া নীরিক্ষা ও হিসাবে দুই জন, আনসারে ১২ জন, শুল্ক ও আবগারীতে ৬৪ জন, সমবায়ে ছয় জন, খাদ্যে চার জন, পররাষ্ট্রে ১৩ জন, পরিবার পরিকল্পনায় চার জন, তথ্যে ১০ জন, ডাকবিভাগে তিন জন, রেলওয়ে পরিবহন ও বাণিজ্যিকে তিন জন, কর প্রশাসনে ২৫ জন, বাণিজ্যে দুই জন, অর্থনীতিতে ৩২ জন, মৎস্যে ১১, স্বাস্থ্যে ১৯৭, সড়ক ও জনপথে ১৮, রেলওয়ে প্রকৌশলে ছয় জন এবং জনস্বাস্থ্য প্রকৌশলে এক জন নিয়োগ পেয়েছেন।

২০০৯ সালের ৪ অগাস্ট ২৯তম বিসিএসের প্রিলিমিনারি পরীক্ষায় অংশ নিয়েছিলো ১ লাখ ২৩ হাজার ৭৪৫ জন। তার মধ্যে উত্তীর্ণ হয়েছিলো ১৩ হাজার ৫৩৬ জন।

প্রিলিমিনারিতে উত্তীর্ণদের লিখিত ও মৌখিক পরীক্ষার পর চূড়ান্ত উত্তীর্ণের তালিকায় মনোনীত হন ৫০৬২ জন। এদের মধ্যে থেকেই ১ হাজার ৪৮০ জনকে নিয়োগ দেওয়া হলো।


Creating Message in JSON with JavaScript("toJSONString()" )

Posted by imomins on July 11, 2011 at 7:12 AM Comments comments (0)

Creating Message in JSON with JavaScript      

In previous section you have studied about the JSONin JavaScript's some basic concepts of creating a simple object and creating anarray of objects. Now we are going to discuss how to create a message with JSONin JavaScript.

In this example of creating message in JSON withJavaScript we have included "json2.js" file first. After thiswe have created an object variable students which contains two array objects .Again we have created an array object and pushed one array data into it. Messageis then created by converting array object to string by using the function "toJSONString()". Here is the example code of CreatingMessage.htm :

CreatingMessage.htm

<html>

<head>

<title>

Creating Message using JSON in JavaScript

</title>

<script language="javascript" src="json2.js"></script>

<script language="javascript" >

 

  var students = { "Maths" : [ 

  { "Name"  : "Amit",    // First element

  "Marks" : 67,

  "age" : 23 },  

  {

  "Name"  : "Sandeep",  // Second element

  "Marks" : 65,

  "age" : 21 }

 ], 

  "Science" : [ 

   { "Name" : "Shaili",  // First Element

 "Marks"  : 56,

 "age"  : 27 }, 

  { "Name"   : "Santosh", // Second Element

 "Marks"  : 78,

 "age"  : 41 }

  ] 

  } 

  // Printing array elements values 

var i=0

var arrayObject = new Array();

for(i=0;i<students.Maths.length;i++)

{  

  arrayObject.push(students.Maths[i].Name);

  arrayObject.push(students.Maths[i].Marks);

  arrayObject.push(students.Maths[i].age);

}  

  alert("Welcome to JSON Message Example ");

  alert(arrayObject.toJSONString());

</script>

</head>

<body>

 Message creation using JSON in JavaScript

</body>

</html>

To run this example you need to include the JavaScriptfile "json2.js" so that the functions defined for convertingobjects to string and parse them can be done. This can be downloaded from http://www.json.org/json2.js

Here is the "json2.js" file code:

/*

json.js

2008-05-25

Public Domain

No warranty expressed or implied. Use at your own risk.

This file has been superceded by http://www.JSON.org/json2.js

See http://www.JSON.org/js.html

This file adds these methods to JavaScript:

array.toJSONString(whitelist)

boolean.toJSONString()

date.toJSONString()

number.toJSONString()

object.toJSONString(whitelist)

string.toJSONString()

These methods produce a JSON text from a JavaScript value.

It must not contain any cyclical references. Illegal values

will be excluded.

The default conversion for dates is to an ISO string. You can

add a toJSONString method to any date object to get a different

representation.

The object and array methods can take an optional whitelist

argument. A whitelist is an array of strings. If it is provided,

keys in objects not found in the whitelist are excluded.

string.parseJSON(filter)

This method parses a JSON text to produce an object or

array. It can throw a SyntaxError exception.

The optional filter parameter is a function which can filter and

transform the results. It receives each of the keys and values, and

its return value is used instead of the original value. If it

returns what it received, then structure is not modified. If it

returns undefined then the member is deleted.

Example:

// Parse the text. If a key contains the string 'date' then

// convert the value to a date.

myData = text.parseJSON(function (key, value) {

return key.indexOf('date') >= 0 ? new Date(value) : value;

});

This file will break programs with improper for..in loops. See

http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

This file creates a global JSON object containing two methods: stringify

and parse.

JSON.stringify(value, replacer, space)

value any JavaScript value, usually an object or array.

replacer an optional parameter that determines how object

values are stringified for objects without a toJSON

method. It can be a function or an array.

space an optional parameter that specifies the indentation

of nested structures. If it is omitted, the text will

be packed without extra whitespace. If it is a number,

it will specify the number of spaces to indent at each

level. If it is a string (such as '\t' or '&nbsp;'),

it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON

method, its toJSON method will be called and the result will be

stringified. A toJSON method does not serialize: it returns the

value represented by the name/value pair that should be serialized,

or undefined if nothing should be serialized. The toJSON method

will be passed the key associated with the value, and this will be

bound to the object holding the key.

  For example, this would serialize Dates as ISO strings.

   Date.prototype.toJSON = function (key) {

   function f(n) {

   // Format integers to have at least two digits.

   return n < 10 ? '0' + n : n;

 }

   return this.getUTCFullYear() + '-' +

  f(this.getUTCMonth() + 1) + '-' +

  f(this.getUTCDate()) + 'T' +

  f(this.getUTCHours()) + ':' +

  f(this.getUTCMinutes()) + ':' +

  f(this.getUTCSeconds()) + 'Z';

};

You can provide an optional replacer method. It will be passed the

key and value of each member, with this bound to the containing

object. The value that is returned from your method will be

serialized. If your method returns undefined, then the member will

be excluded from the serialization.

If the replacer parameter is an array, then it will be used to

select the members to be serialized. It filters the results such

that only members with keys listed in the replacer array are

stringified.

Values that do not have JSON representations, such as undefined or

functions, will not be serialized. Such values in objects will be

dropped; in arrays they will be replaced with null. You can use

a replacer function to replace those with JSON values.

JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the

value that is filled with line breaks and indentation to make it

easier to read.

If the space parameter is a non-empty string, then that string will

be used for indentation. If the space parameter is a number, then

the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);

// text is '["e",{"pluribus":"unum"}]'

text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');

// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {

return this[key] instanceof Date ?

'Date(' + this[key] + ')' : value;

});

// text is '["Date(---current time---)"]'

JSON.parse(text, reviver)

This method parses a JSON text to produce an object or array.

It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and

transform the results. It receives each of the keys and values,

and its return value is used instead of the original value.

If it returns what it received, then the structure is not modified.

If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will

// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {

var a;

if (typeof value === 'string') {

a =

/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);

if (a) {

return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],

+a[5], +a[6]));

}

}

return value;

});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {

var d;

if (typeof value === 'string' &&

value.slice(0, 5) === 'Date(' &&

value.slice(-1) === ')') {

d = new Date(value.slice(5, -1));

if (d) {

return d;

}

}

return value;

});

It is expected that these methods will formally become part of the

JavaScript Programming Language in the Fourth Edition of the

ECMAScript standard in 2008.

This is a reference implementation. You are free to copy, modify, or

redistribute.

This code should be minified before deployment.

See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU

DO NOT CONTROL.

*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,

charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,

getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,

parse, parseJSON, propertyIsEnumerable, prototype, push, replace, slice,

stringify, test, toJSON, toJSONString, toString

*/

if (!this.JSON) {

// Create a JSON object only if one does not already exist. We create the

// object in a closure to avoid global variables.

JSON = function () {

function f(n) {

// Format integers to have at least two digits.

return n < 10 ? '0' + n : n;

}

Date.prototype.toJSON = function (key) {

return this.getUTCFullYear() + '-' +

f(this.getUTCMonth() + 1) + '-' +

f(this.getUTCDate()) + 'T' +

f(this.getUTCHours()) + ':' +

f(this.getUTCMinutes()) + ':' +

f(this.getUTCSeconds()) + 'Z';

};

var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5

\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,

escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5

\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,

gap,

indent,

meta = { // table of character substitutions

'\b': '\\b',

'\t': '\\t',

'\n': '\\n',

'\f': '\\f',

'\r': '\\r',

'"' : '\\"',

'\\': '\\\\'

},

rep;

function quote(string) {

// If the string contains no control characters, no quote characters, and no

// backslash characters, then we can safely slap some quotes around it.

// Otherwise we must also replace the offending characters with safe escape

// sequences.

escapeable.lastIndex = 0;

return escapeable.test(string) ?

'"' + string.replace(escapeable, function (a) {

var c = meta[a];

if (typeof c === 'string') {

return c;

}

return '\\u' + ('0000' +

(+(a.charCodeAt(0))).toString(16)).slice(-4);

}) + '"' :

'"' + string + '"';

}

function str(key, holder) {

// Produce a string from holder[key].

var i, // The loop counter.

k, // The member key.

v, // The member value.

length,

mind = gap,

partial,

value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

if (value && typeof value === 'object' &&

typeof value.toJSON === 'function') {

value = value.toJSON(key);

}

// If we were called with a replacer function, then call the replacer to

// obtain a replacement value.

if (typeof rep === 'function') {

value = rep.call(holder, key, value);

}

// What happens next depends on the value's type.

switch (typeof value) {

case 'string':

return quote(value);

case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

return isFinite(value) ? String(value) : 'null';

case 'boolean':

case 'null':

// If the value is a boolean or null, convert it to a string. Note:

// typeof null does not produce 'null'. The case is included here in

// the remote chance that this gets fixed someday.

return String(value);

// If the type is 'object', we might be dealing with an object or an array or

// null.

case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',

// so watch out for that case.

if (!value) {

return 'null';

}

// Make an array to hold the partial results of stringifying this object value.

gap += indent;

partial = [];

// If the object has a dontEnum length property, we'll treat it as an array.

if (typeof value.length === 'number' &&

!(value.propertyIsEnumerable('length'))) {

// The object is an array. Stringify every element. Use null as a placeholder

// for non-JSON values.

length = value.length;

for (i = 0; i < length; i += 1) {

partial[i] = str(i, value) || 'null';

}

// Join all of the elements together, separated with commas, and wrap them in

// brackets.

v = partial.length === 0 ? '[]' :

gap ? '[\n' + gap +

partial.join(',\n' + gap) + '\n' +

mind + ']' :

'[' + partial.join(',') + ']';

gap = mind;

return v;

}

// If the replacer is an array, use it to select the members to be stringified.

if (rep && typeof rep === 'object') {

length = rep.length;

for (i = 0; i < length; i += 1) {

k = rep[i];

if (typeof k === 'string') {

v = str(k, value, rep);

if (v) {

partial.push(quote(k) + (gap ? ': ' : ':') + v);

}

}

}

} else {

// Otherwise, iterate through all of the keys in the object.

for (k in value) {

if (Object.hasOwnProperty.call(value, k)) {

v = str(k, value, rep);

if (v) {

partial.push(quote(k) + (gap ? ': ' : ':') + v);

}

}

}

}

// Join all of the member texts together, separated with commas,

// and wrap them in braces.

v = partial.length === 0 ? '{}' :

gap ? '{\n' + gap +

partial.join(',\n' + gap) + '\n' +

mind + '}' :

'{' + partial.join(',') + '}';

gap = mind;

return v;

}

}

// Return the JSON object containing the stringify and parse methods.

return {

stringify: function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional

// space parameter, and returns a JSON text. The replacer can be a function

// that can replace values, or an array of strings that will select the keys.

// A default replacer method can be provided. Use of the space parameter can

// produce text that is more easily readable.

var i;

gap = '';

indent = '';

// If the space parameter is a number, make an indent string containing that

// many spaces.

if (typeof space === 'number') {

for (i = 0; i < space; i += 1) {

indent += ' ';

}

// If the space parameter is a string, it will be used as the indent string.

} else if (typeof space === 'string') {

indent = space;

}

// If there is a replacer, it must be a function or an array.

// Otherwise, throw an error.

rep = replacer;

if (replacer && typeof replacer !== 'function' &&

(typeof replacer !== 'object' ||

typeof replacer.length !== 'number')) {

throw new Error('JSON.stringify');

}

// Make a fake root object containing our value under the key of ''.

// Return the result of stringifying the value.

return str('', {'': value});

},

parse: function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns

// a JavaScript value if the text is a valid JSON text.

var j;

function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so

// that modifications can be made.

var k, v, value = holder[key];

if (value && typeof value === 'object') {

for (k in value) {

if (Object.hasOwnProperty.call(value, k)) {

v = walk(value, k);

if (v !== undefined) {

value[k] = v;

} else {

delete value[k];

}

}

}

}

return reviver.call(holder, key, value);

}

// Parsing happens in four stages. In the first stage, we replace certain

// Unicode characters with escape sequences. JavaScript handles many characters

// incorrectly, either silently deleting them, or treating them as line endings.

cx.lastIndex = 0;

if (cx.test(text)) {

text = text.replace(cx, function (a) {

return '\\u' + ('0000' +

(+(a.charCodeAt(0))).toString(16)).slice(-4);

});

}

// In the second stage, we run the text against regular expressions that look

// for non-JSON patterns. We are especially concerned with '()' and 'new'

// because they can cause invocation, and '=' because it can cause mutation.

// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around

// crippling inefficiencies in IE's and Safari's regexp engines. First we

// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we

// replace all simple value tokens with ']' characters. Third, we delete all

// open brackets that follow a colon or comma or that begin the text. Finally,

// we look to see that the remaining characters are only whitespace or ']' or

// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

if (/^[\],:{}\s]*$/.

test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').

replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').

replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a

// JavaScript structure. The '{' operator is subject to a syntactic ambiguity

// in JavaScript: it can begin a block or an object literal. We wrap the text

// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing

// each name/value pair to a reviver function for possible transformation.

return typeof reviver === 'function' ?

walk({'': j}, '') : j;

}

// If the text is not JSON parseable, then a SyntaxError is thrown.

  throw new SyntaxError('JSON.parse');

}

};

}();

}

// Augment the basic prototypes if they have not already been augmented.

// These forms are obsolete. It is recommended that JSON.stringify and

// JSON.parse be used instead.

if (!Object.prototype.toJSONString) {

Object.prototype.toJSONString = function (filter) {

return JSON.stringify(this, filter);

};

Object.prototype.parseJSON = function (filter) {

return JSON.parse(this, filter);

};

} To run this example open the CreateMessage.htm onthe browser and the output on the browser will look like this:

 


Creating Array Objects in JavaScript with JSON

Posted by imomins on July 11, 2011 at 6:59 AM Comments comments (0)

Creating Array Objects in JavaScript with JSON      

In the previous section of JavaScript-JSON tutorial youhave known that how to create an object and now in this tutorial we haveprovided you the way array of objects are declared in JavaScript-JSON.

In our example file we have created an object "students"which contains two array objects "Maths" and "Science"containing name, marks and age of two students. Now we  can access theseobjects value in the following way:

"students.Maths" for accessing Mathsarray and "students.Science" for accessing Science arrayobject. Now to access first element of the Maths array we can write it as"students.Maths[1]" and then we can access elements of thisarray as "students.Maths[1].Name" for name and "students.Maths[1].Marks"for marks of the first student in Maths and so on.

Here is the full example code for JavaScript-JSONArray.htmfile.

JavaScript-JSONArray.htm

<html>

<head>

<title>

Array JSON-JavaScript Example

</title>

<script language="javascript" >

var students = { "Maths" : [      {"Name" : "Amit", // First element

  "Marks" : 67,

 "age" : 23 },

{"Name"  : "Sandeep",  // Second element

 "Marks" : 65,

 "age" : 21 }

 ], 

"Science" :  [

{"Name"  : "Shaili",  // First Element

 "Marks" : 56,

 "age" : 27 },  

  "Name"  : "Santosh",  // Second Element

  "Marks" : 78,

 "age" : 41 }

 ] 

  } 

  // Printing all array values 

var i=0

document.writeln("<table border='1'><tr>");

for(i=0;i<students.Maths.length;i++)

{  

  document.writeln("<td>");

  document.writeln("<table border='0'  width=100 >");

  document.writeln("<tr><td><B>Name</B></td><td width=50>"

  +students.Maths[i].Name+"</td></tr>");

  document.writeln("<tr><td><B>Marks</B></td><td width=50>"

  +students.Maths[i].Marks +"</td></tr>");

  document.writeln("<tr><td><B>Age</B></td><td width=50>"

  +students.Maths[i].age +"</td></tr>");

  document.writeln("</table>");

  document.writeln("</td>");

}

for(i=0;i<students.Science.length;i++)

{

  document.writeln("<td>");

  document.writeln("<table border='0'  width=100 >");

  document.writeln("<tr><td><B>Name</B></td><td width=50>"

   +students.Science[i].Name+"</td></tr>");

  document.writeln("<tr><td><B>Marks</B></td><td width=50>"

   +students.Science[i].Marks +"</td></tr>");

  document.writeln("<tr><td><B>Age</B></td><td width=50>"

   +students.Science[i].age +"</td></tr>");

  document.writeln("</table>");

  document.writeln("</td>");

}

document.writeln("</tr></table>");

</script>

</head>

<body>

Using Array of objects via JSON in JavaScript

</body>

</html>

 


JSON in JavaScript

Posted by imomins on July 11, 2011 at 6:47 AM Comments comments (0)

JSON stands for JavaScript Object Notation that is a language independent text format which is fast and easy to understand.

JSON in JavaScript      

JSON stands for JavaScriptObject Notationthat  is a language independent text format which is fast and easy to understand.That means it is really very simple and easy to learn without sparing much time.In another words we can say that JavaScriptObject Notation is a lightweight data-interchangeformat that iscompletely language independent but with some conventions. 

So in thissection of JSON tutorial we are going to discuss JSON  with JavaScript. 

Creating Object in JavaScript using JSON

We can create objects in JSON with JavaScript in manyways :

1. "var JSONObjectName ={};" willcreate an empty object. 

2. "var JSONObjectName= new Object();"will create a new Object.

3. "var JSONObjectName = { "name":"amit", "age":23}; will create an Object withattribute name which contains value in String and age with numericvalue.

Now by creating this object we can access attributes byonly "." operator.

Here is the full example code for creating an Object inJavaScript using JSON:

ObjectJavaScript-JSON.htm

<html>

<head>

<title>

 Object creation in JSON in JavaScript

</title>

<script language="javascript" >

var JSONObject = {  "name" : "Amit",

  "address"  : "B-123 Bangalow",

  "age"  : 23, 

  "phone"   : "011-4565763",

   "MobileNo"  : 0981100092

  };

document.write("<h2><font color='blue'>Name</font>::"

   +JSONObject.name+"</h2>");  

document.write("<h2><font color='blue'>Address</font>::"

   +JSONObject.address+"</h2>");  

document.write("<h2><font color='blue'>Age</font>::"

   +JSONObject.age+"</h2>");  

document.write("<h2><font color='blue'>Phone No.</font>::"

   +JSONObject.phone+"</h2>");  

document.write("<h2><font color='blue'>Mobile No.</font>::"

   +JSONObject.MobileNo+"</h2>");  

</script>

</head>

<body>

<h3>Example of object creation in JSON in JavaScript</h3>

</body>

</html>

 


Introduction to JSON

Posted by imomins on July 11, 2011 at 6:45 AM Comments comments (0)

Introduction to JSON Introduction

As we know Ajax is a web development technology that makes the server responses faster by enabling the client-side scripts to retrieve only the required data from the server without retrieving a complete web page on each request, which will minimize the data transferred from the server.

These requests usually retrieve xml formatted response, the xml responses are then parsed in the JavaScript code to render the results. Which complicate the JavaScript code

The idea of JSON (JavaScript Object Notation) is to make the response a specific data structure that can be easily parsed by the JavaScript code.

Advantages

1- lightweight data-interchange format

2- Easy for humans to read and write

3- Easy for machines to parse and generate

4- JSON can be parsed trivially using the eval() procedure in JavaScript

5- JSON Supports: ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.

.

Syntax

The JSON Syntax is the convention which you will use it to generate data, it’s near to the C family language, so it can be parsed easily in the C family languages.

For objects start the object with “{“ and end it with “}”

object

{}

{ members }

·         For members (properties), use pairs of string : value and separate them by commas

members

string : value

members , string : value

·         For arrays put the arrays between []

array

[]

[ elements ]

·         For elements put the values directly separated by commas

elements

value

elements , value

·         Values can be  string, number, object, array, true, false, null

EXAMPLESJSON 

{"menu": {  

  "id": "file",

  "value": "File:",  

  "popup": {  

    "menuitem": [ 

      {"value": "New", "onclick": "CreateNewDoc()"},

      {"value": "Open", "onclick": "OpenDoc()"},  

      {"value": "Close", "onclick": "CloseDoc()"}  ]

  }

}}

XML<menu id="file" value="File" >  <popup>     <menuitem value="New" onclick="CreateNewDoc()" />     <menuitem value="Open" onclick="OpenDoc()" />     <menuitem value="Close" onclick="CloseDoc()" />  </popup></menu>

 

 

 

 

 

Server side codeThe following code will be generated in the server side to retrieve the server time, and in one step in the client side it will be rendered to JavaScript

Java <%@ page language="java" import="java.util.*" %>

<%Date date = new Date(); %>alert("The server time is: <%Úte%>");

<SPAN style="mso-tab-count: 1" mce_style="mso-tab-count: 1">          ASP.NET<%@ page language="C#" %>   alert("The server time is: <%=System.Date.Now.ToString()%>"); 

PHPalert("The server time is: <?=time()?>"); 

Client Side JavaScript//XMLHttpRequest completion function

var myOnComplete = function(responseText, responseXML){eval(responseText);}

 

 

 

 

 

 

 

 

 

 

 

 



Rss_feed