Pages

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, February 12, 2014

Javascript - Work With JSON Datetime

Sometimes when we work with JSON datetimes we get a little stuck, because we want to do all the work client side, using javascript only.

 So, to achieve this, to transform something like this:

"/Date(1392291352347)/"

into this:

"2014-02-13 11:35:52"

we can use a function like this one:

function formatDatetime(jsondate) {

    var match;
    if (jsondate == null || !(match = jsondate.match(/\d+/))) {
        return "";
    }

    var d = new Date();
    d.setTime(match[0] - 0);

    var month = d.getMonth() + 1;
    var day = d.getDate();
    var hour = d.getHours();
    var minute = d.getMinutes();
    var second = d.getSeconds();

    var output = d.getFullYear() + '-' +
    (('' + month).length < 2 ? '0' : '') + month + '-' +
    (('' + day).length < 2 ? '0' : '') + day + ' ' +
    (('' + hour).length < 2 ? '0' : '') + hour + ':' +
    (('' + minute).length < 2 ? '0' : '') + minute + ':' +
    (('' + second).length < 2 ? '0' : '') + second;

    return output;
}

References:
http://stackoverflow.com/questions/9050763/format-date-in-jquery
http://stackoverflow.com/questions/4586424/how-do-i-convert-this-json-datetime

Tuesday, March 12, 2013

Endpoint on ASP.NET page returning JSON from DataTable

I was trying to get an web service, on my aspx page which returned data would be JSON.

The structure of JSON returned usually is something similar to this:

{ "d" :  [ {...}, {...}, {...} ] }

To achieve this, I purpose this approach:


First - Create an WebMethod on your page, at server side, like this:

        [System.Web.Services.WebMethod]
        public static string GetData()
        {
            DataTable dt = GetDataTable();
            
            return BuildJSONFromDT(dt);
        }



Second - Create the method "BuildJSONFromDT"

 

        private static string BuildJSONFromDT(DataTable dt)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            List<object> resultMain = new List<object>();

            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn column in dt.Columns)
                {
                    result.Add(column.ColumnName, "" + row[column.ColumnName]);
                }

                resultMain.Add(result);
            }

            return serializer.Serialize(resultMain);
        }



Third - At client side, do an ajax call with jquery like this:

$.ajax({
        type: "POST",
        async: true,
        contentType: "application/json; charset=utf-8",
        data: "{}",
        url: "page.aspx/GetData",
        dataType: "json",
        success: function (result) {
            var myData = eval(result.d);
            // Work on myData object (JSON)
        },
        error: function (data, textStatus, jqXHR) {
            alert("Error: " + textStatus);
        }
    });



At this point, you should have an valid JSON at client side reflecting your DataTable retrieved on server side.

Hope this helps someone.

Cheers!


Reference:
http://geekswithblogs.net/aghausman/archive/2009/05/16/datatable-to-json.aspx

Monday, August 27, 2012

Request JSON using WCF DS 5.0

So, I was start using WCF OData Services 5.0.1.0 and when I made an ajax call requesting the response in JSON I get the 415 error: "Unsupported media type requested".

Detail: "A supported MIME type could not be found that matches the acceptable MIME types for the request. The supported type(s) 'application/atom+xml;type=feed, application/atom+xml, application/json;odata=verbose' do not match any of the acceptable MIME types 'application/json'".

This happens because the serialization json light format will be part of the OData v3 protocol: "The new serialization format will be part of the OData v3 protocol, and we believe that the much-improved JSON format should be the default response when requesting application/json." (http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx)

In conclusion, you have the next code on your WCF OData Service:
public class api : DataService <DataModel>
{
 public static void InitializeService(DataServiceConfiguration config)
 {
  config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
  config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
 }
}



And to call the service using javascript/jquery you can use the next code for that:
$.ajax({
  type: "GET",
  url: "api.svc/Entity()?$top=10",
  dataType: "json",
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Accept", "application/json;odata=verbose");
  },
  success: function (data) {
    //success func
  },
  error: function (error) {
    //error func
  }
});


References:
http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx
http://blogs.msdn.com/b/astoriateam/archive/2012/04/09/wcf-data-services-5-0-rtm-release.aspx
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataservices/thread/ae80bb85-ad26-48c4-a399-4d76db5c346b

Wednesday, August 22, 2012

jqGrid - External/Custom Filters (not the filtertoolbar)

So, I had the need to filter an jqgrid data, but without using the in-built filtertoolbar (btw is really good...).

To achieve this objective, we have to make the reload of the grid with the new filters... manually...

Now, to filter we need to add/alter the postdata.filters.rules object of the grid. With the search I made, I came up with this function that, perhaps, can help someone...

function OnChangeGridSelect (fieldName, searchText) {    
    var filterObj = {"field":fieldName,"op":"eq","data":searchText};
    var grid = jQuery("#GridID");
    var postdata = grid.jqGrid('getGridParam', 'postData');

    if(postdata != undefined 
       && postdata.filters != undefined 
       && postdata.filters.rules != undefined) 
    {
        //Remove if current field exists
        postdata.filters.rules = $.grep(postdata.filters.rules, function(value) {
            if(value.field != fieldName)
                return value;
        });

        //Add new filter
        postdata.filters.rules.push(filterObj);
    }
    else 
    {
        $.extend(postdata, {
            filters:  { 
                "groupOp":"AND",
                "rules":[ filterObj ] 
            }
        });
    }

    grid.jqGrid('setGridParam', { search: true, postData: postdata });
    grid.trigger("reloadGrid", [{ page: 1}]);
}

explaining the parameters of the above function:
- fieldName is the internal name of the collumn we want to filter with
- searchText is the text from you want to filter the grid.

In my example, the function is called inside combos's events with the necessary parameters.

Approximate result...

















If you don not know the jqgrid here are a couple of links to get into:
http://trirand.com/blog/jqgrid/jqgrid.html
http://www.trirand.com/jqgridwiki/doku.php

Cheers


References:
http://stackoverflow.com/questions/4492963/jqgrid-client-side-searching
http://stackoverflow.com/questions/5749723/jqgrid-filtering-records
http://www.codeproject.com/Articles/58357/Using-jqGrid-s-search-toolbar-with-multiple-filter#pre4
http://stackoverflow.com/questions/2674471/add-own-search-parameter-in-jqgrid-in-asp-net-mvc#answer-2679599

Thursday, February 09, 2012

Using JQuery To Alter Sharepoint Toolbar Menu Item

So... I was trying to change the text of a menu option on a list toolbar in Sharepoint 2007 like this one...








The Purpose of this was to change the text on the menu without changing the content type name. This is really needed when you extend your sharepoint at the point that to change a content type name is not worthy!

After some search, I found a really simple way to do it! check it above.

//Get tag  and change it's attribute
$("ie\\:menuitem[text='Request']").attr("text", "Order");



References:
http://sharepoint.stackexchange.com/questions/2195/modification-of-layouts-upload-aspx

Monday, May 30, 2011

Clear Authentication Cache - Javascript

If we use http authentication, at the moment we want to logout a user for good, there's some issues we have to be aware of. So, we want to logout a user at client side and make sure that no one else has access to his/her account when using the same browser to access the same portal for instance. For IE, early versions, is pretty easy, we just do the code below:

// Clear current credentials
// Requires IE6 SP1 or later
document.execCommand(ClearAuthenticationCache)


Unfortunately, the ClearAuthenticationCache command is not available to others browsers in this case, so in order to do this really need to close the browser or, if it works for you, make an ajax call with wrong credentials to make your latest credentials saved to browser authentication cache be a 401 for that site. Mixing this all together we can have a javascript code like this one:




























References:
http://www.adopenstatic.com/cs/blogs/ken/archive/2005/04/12/14.aspx
http://stackoverflow.com/questions/31326/is-there-a-browser-equivalent-to-ies-clearauthenticationcache
http://stackoverflow.com/questions/1205045/how-to-clear-authentication-cache-on-ie7-with-javascript
http://www.nanodocumet.com/?p=6
http://msdn.microsoft.com/en-us/library/ms536979(v=vs.85).aspx
http://code.google.com/p/chromium/issues/detail?id=5497
http://trac-hacks.org/wiki/TrueHttpLogoutPatch

Tuesday, March 15, 2011

jQuery - Dynamic Table Creation Using Templates

Sometimes you really need to do things at client side, and one of them could be like a table creation with data on demand. Example, if you do a jQuery Ajax call, receive data in JSON format and present this data in a table, this is a pretty good and clean approach.

The example code goes like this:


































As you can see above, is simple and clean, even if you want to apply classes to <tr> or <td> tags for instance. The expected result from this code is a really dummy table.











References:
http://api.jquery.com/jquery.tmpl/

Wednesday, February 16, 2011

Post JSON to MVC Controller with XDomainRequest, XmlHttpRequest and jQuery Ajax Call

Once I try to post a JSON to a MVC controller, I use jQuery.post method and all works fine as you can see in this site, the first in the below references.

But when I try to use XDomainRequest or XmlHttpRequest, the JSON parameter at server side has null properties, in others words, the data is sent but not serialized to our serializable Type.

So, in order to receive data at server side, i used the DataContractJsonSerializer class to read the Stream sent in the Request, like this:





Of course, to make use of DataContractJsonSerializer, we need a class representing JSON with [DataContract] attribute and respective [DataMember] just like a WCF service for instance.

Then, the code at server side, looks like this:































And, at client side, making use of XDomainRequest and XmlHttpRequest Objects, and jquery the code is






















This way, you have a MCV controller that can receive JSON using the JSON serializing capacities of MCV3 from XDomainRequest, XmlHttpRequest and jQuery ajax call.


References:
http://lozanotek.com/blog/archive/2010/04/16/posting_json_data_to_mvc_controllers.aspx
http://msdn.microsoft.com/en-us/library/bb412170.aspx
http://msdn.microsoft.com/en-us/library/bb412179.aspx

Monday, February 14, 2011

Javascript - Consume Service With Cross Domain Request

Every time you need to do a request over your domain, you have to be aware of what kind of browser is running your code. If is an IExplorer, you will need to use the object XDomainRequest because this object is specifically to make cross-domain requests.

Here's a sample of usage:









If you want to make it complaint with others browsers you will need to use the XmlHttpRequest object, or, even simpler, making an ajax call with jQuery. This object, together with CORS, make possible to make cross domain requests.

The snippet of XmlHttpRequest goes like this:







And the call using jQuery:













XDomainRequest is the response by Microsoft against XmlHttpRequest with CORS protocol, instead of integrate it (CORS) with IExplorer, they create their own object for cross domain's requests.

Regarding CORS, all you have to do, is making your service server aware for OPTIONS verb and return the needed headers, because the browser itself makes the magic happens. So, to enable cross domain ajax call, at server you need to...



















With all this set up, you should have your communication with your server on. One little note, be aware of kind of service and object you are using, for instance, XDomainRequest only accept text/plain to send (xdr.send(string)) and an WCF service accepts XML, JSON, etc. but not text/plain.


References:
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
http://stackoverflow.com/questions/4739384/xdomainrequest-problem
http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
http://www.codeproject.com/KB/ajax/jQueryWCFRest.aspx

Monday, January 31, 2011

Javascript - Catch Unhandled Exceptions

Have you ever thought to manage all exceptions at client side? if you use a simple line of code, like the one presented below, you can get an simple message and direct you to the right way to solve the script problem.










The window.onerror is an event handler for errors events sent to the window, catching all Unhandled Exceptions. But this approach has the problem that only works on IE or Gecko based browsers. It's a damn limitation for sure...

BTW, in order to test the onerror event, use a simple code line like "color[2]" without any initializing letting the script get error, then you'll see the alert window.



References:
https://developer.mozilla.org/En/DOM/Window.onerror
http://stackoverflow.com/questions/339580/does-javascript-fire-an-event-for-unhandled-uncaught-exceptions
http://stackoverflow.com/questions/1008692/window-onerror-not-firing-in-firefox