Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Thursday, 1 March 2012

JQuery multiselect selectedText does not work with JQuery > 1.4.2 when select list contains only one element

This is the problem with the change in the jquery version. Previous jquery(up to 1.4.2) the checkbox checked can be found by using "[checked]". Later versions of jquery changed to ":checked". To fix this issue go the jquery multiselect plugin js file line number 206 and change  $checked = $inputs.filter('[checked]') to $checked = $inputs.filter(':checked'). This solution works for me.

Monday, 20 February 2012

Jquery Ajax Request and Unauthorized Access handling in MVC3

When we are posting the data through jquery $.ajax and  we are using asp.net forms authentication, if the user is not authorized then we will redirect to the login page. the same login page response is return result as on jquery ajax success. If we throw any exception in controller or any custom authorize attribute then ajax request returns the 500 status code internal server exception as its default behaviour. 500 status code reruns any exception in the request processing. But our view is to return the 401 as the status code. I research about many hours to get this solution.

Solution1:

1. Custom authentication attribute
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }

}
If the user is not authenticated the reruns to logon action as i am using forms authentication in asp.net.
2. In the controller action result write the following
 public ActionResult Logon()
 {
  if (Request.IsAjaxRequest())
  {
 
  //this is used when the authentication fails in the ajax request
  //this returns the httpstatus code 401 to the browser.
 
   ControllerContext.HttpContext.Response.StatusCode = 401;
 
   return Content(string.Empty);
  
   }

 } 
3. Handle the status codes in jquery $.ajaxSetup
$.ajaxSetup({
             statusCode: {
                        401: function () {
 
                            // Redirect the to the login page.
                            window.location = "/login/";
 
                        }
                    }
            });
Solution2:
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }


public override void OnAuthorization(AuthorizationContext filterContext)
{
   base.OnAuthorization(filterContext);

  // If its an unauthorized/timed out ajax request go to top window and redirect to logon.
    if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
    {
filterContext.Result = new JavaScriptResult() { Script = "top.location.reload()"    };
    }

  // If authorization results in HttpUnauthorizedResult, redirect to error page instead of Logon page.
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                if (ClientContext.Current.User == null)
                {
                    filterContext.Result =
                        new RedirectResult(
                            string.Format(
                                "~/logon/logon?ReturnUrl={0}",
                                HttpUtility.HtmlEncode(filterContext.HttpContext.Request.RawUrl)));
                }
                else
                {
                    filterContext.Result =
                       new RedirectResult(string.Format("~/error/unauthorized"));
                }
            }
        }
}
I hope this will help you. 

Monday, 6 June 2011

How to identify is image is loaded or not using jquery. If image notloaded loading the default image

When we are working with websites some times images may failed to load. To Identify is the image is loaded or not the follwing is the solution.
Solution 1
function IsImageLoaded() {
if($('#img_id').attr('complete')){
alert('Image is loaded!');
return true;
} else {
return false;
}
}
Solution 2
$("#photo").error(function() {
alert("Image failed to load");
});

Sunday, 17 April 2011

Working with jquery key events

The key events are always required to use in application when we dont want to use mouse. the following is the example to handle key events using key codes in jqurery. for all javascript key codes refer http://vikramdoda.wordpress.com/2011/04/10/javascript-key-codes/

Syntax for handle keypress event is
.keypress( [ eventData ], handler(eventObject) )
eventDataA map of data that will be passed to the event handler.
handler(eventObject)A function to execute each time the event is triggered.
<script> var xTriggered = 0;
 $('#target').keypress(function(event) { 
  if (event.which == '13') {   
   event.preventDefault();   
 }  
  xTriggered++;   
 var msg = 'Handler for .keypress() called ' + xTriggered + ' time(s).';  
 $.print(msg, 'html'); 
  $.print(event);
 });
 </script>

Tuesday, 22 March 2011

Jquery making synchronous Ajax call

Difference between Synchronous and Asynchronous
  • Synchronous is where the script stops and waits for the server to send back a reply before continuing
  • Asynchronous is where the script allows the page to continue to be processed and will handle the reply if and when it arrives.
$.ajax({
type: "POST",
url: "url of the page",
processData: false,
success: function(msg) {alert("success")},
async:false 
});
If you see the last line, the attribute declaration async:false which is the key for the telling the Jquery client proxy to make asynchronous call or not. If it is true then asynchronous otherwise synchronous. By default it is asynchronous.

Function for centering an Element

Example function for centering an element is shown below.
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}


//We can call the method as follows:
$("#popup").center();

Creating our own functions in jquery

The basis of creating a our own jQuery function is actually quite simple. The following is an example to create function:

The structure required to extend the jQuery.fn object and create our own function is…
jQuery.fn.firstFunction = function () {
return this.each (function () {
alert (this.id);
});
}
You’d now be able to call your function as you normally would call any other jquery function
$('#test').firstFunction();
This would display a “nice” alert box showing the element id.

JQuery conflict when using different javascript libraries

If your application is using both JQuery and Prototype libraries(ex: External js file which are using $(.) to get the objects). Both are operating with $() to access the objects and do the client side logic. But, the $() is getting conflicted between JQuery and Prototype libraries.

The solution to resolve the conflict:

If you are using JQuery in your applications, the best practice is declare the Jquery global instance variable and then start using that variable instead of directly use the $().

For example,
var $j = jQuery.noConflict(); 
// Use jQuery via $j(...) instead of $(...)
$j(document).ready(function(){ 
$j("#someId").hide(); 
}); 

Monday, 21 March 2011

Using JQuery intellisence in visual studio.

Steps to Enable jQuery Intellisense in VS 2008


To enable intellisense completion for jQuery within VS you'll want to follow three steps:

Step 1: Install VS 2008 SP1

VS 2008 SP1 adds richer JavaScript intellisense support to Visual Studio, and adds code completion support for a broad range of JavaScript libraries.

Step 2: Install VS 2008 Patch KB958502 to Support "-vsdoc.js" Intellisense Files

A patch that you can apply to VS 2008 SP1 and VWD 2008 Express SP1 that causes Visual Studio to check for the presence of an optional "-vsdoc.js" file when a JavaScript library is referenced, and if present to use this to drive the JavaScript intellisense engine.

These annotated "-vsdoc.js" files can include XML comments that provide help documentation for JavaScript methods, as well as additional code intellisense hints for dynamic JavaScript signatures that cannot automatically be inferred. You can learn more about this patch here. You can download it for free here.

Step 3: Download the jQuery-vsdoc.js file

Download  jQuery-vsdoc.js file that provides help comments and support for JavaScript intellisense on chained jQuery selector methods. You can download both jQuery and the jQuery-vsdoc file from the official download page on the jQuery.com site:


Save the jquery-vsdoc.js file and your jquery.js file in the same folder of your project (and make sure its naming prefix matches the jquery file name):


You can then reference the standard jquery file with an html <script/> element like so:
<script src="jquery-1.2.6.js" type="text/javascript"></script>

<% if (false) { %> 
 <script src="jquery-1.2.6-vsdoc.js" type="text/javascript"></script>  <% } %>

Or alternatively reference it using the <asp:scriptmanager/> control, or by adding a /// <reference/> comment at the top of a standalone .js file.

For example, we could use jQuery to make a JSON based get request, and get intellisense for the method (hanging off of $.):


Note: Jquery intellisense works in Visual Studio 2010 without any Fix downloading and installing.(i.e, eliminate the step2 from the above steps) and also no need to refer the vs-doc in if else if we write internal scripts for VS2010.

To use jquery intellisense in external JavaScript file

Add the following statement at the top of the external JavaScript file
/// <reference path="jquery-1.2.6-vsdoc.js" />