Archive

Posts Tagged ‘JavaScript’

JavaScript: How to determine whether a variable has a valid value

November 29th, 2012 Admin No comments

    A good way to examine whether a variable (or object’s field) has a valid value looks like the following:

if( variable /* obj.field */ ) {
}

This statement allows to check if the value is null (explicit assignment of null to variable happened) or undefined (variable wasn’t initialized). To be more precise it returns true when the variable is not

  • null
  • undefined
  • NaN
  • empty string (“”)
  • 0
  • false

Mostly, such validity check is more than enough for further safe treating with the variable. However, we’ll get the “‘variable’ is undefined error” if the variable is undeclared. In this case we have to perform the following check in advance:

if(typeof variable !== 'undefined') {
}

Of course, if you are pretty sure that the variable exists (is declared), you can omit the typeof check. But if you deal with something going from an external library or source, I recommend having it. So, gathering all together, we obtain the following code:

if(typeof variable !== 'undefined' && variable) {
}

In some forums, people from time to time suggest to wrap such check into a function. Let’s assume we have such function:

function isValid(obj) {
  return typeof obj !== 'undefined' && obj;
}

However, it doesn’t make sense at all as you can’t call the function, passing an undeclared variable, in any case. The mentioned above error is thrown whenever you try addressing to the unknown variable:

if(isValid(varibale)) // throw "'variable' is undefined error",
                      // if the variable doesn't exist
  ...

Thus, in case of undeclared variable, we have to have inline typeof check. In all other cases, it’s enough to have simple if(variable). So, using variables and objects likely declared outside of my code, I examine them like in the sample below:

if(typeof navigator != "undefined" && navigator && navigator.userAgent)
     alert(navigator.userAgent);
Categories: JavaScript, jQuery Tags: ,

jQuery: IsNullOrEmpty plugin for jQuery

November 20th, 2012 Admin No comments

    I was a bit disappointed when couldn’t find in jQuery library a method similar to String.IsNullOrEmpty from C#. So, below is a simple jQuery plugin to examine whether the passed string is empty or null.

(function ($) {
    $.isNullOrEmpty = function (str) {
        return !str || $.trim(str) === ""; // the trim method is provided by jQuery
    };
})(jQuery);

Some samples of use

var res = $.isNullOrEmpty(''); // true
res = $.isNullOrEmpty("bla-bla-bla"); // false
res = $.isNullOrEmpty(null); // true
res = $.isNullOrEmpty(); // true
Related posts:
Categories: JavaScript, jQuery Tags: ,

SharePoint: Issue with calling an asmx web service in SharePoint 2010 through jQuery

November 20th, 2012 Admin No comments

    After migration a SharePoint 2007 application to SharePoint 2010 my jQuery scripts communicating with asmx web services stopped working. The error I got was a 500 Internal Server Error. The scripts looks as follows:

$.ajax({
  type: "POST",
  url:  "http://someserver/someapp/_layouts/Services/Products.asmx/GetProductByCountry",

  data:        JSON.stringify({ countryCode: "USA" }),
  dataType:    "json",
  contentType: 'application/json; charset=utf-8',
  context:     this,

  success: function (data) {
		     alert(data.d);
           },
  error:   function (XMLHttpRequest, textStatus, errorThrown) {
		     alert(textStatus);
           }
});

Note: The JSON object mentioned in the script is defined in the json2.js available at http://www.json.org.

This issue can be solved by adding an appropriate <webServices> section to the SharePoint application’s web.config (in my case it’s located at C:\inetpub\wwwroot\wss\VirtualDirectories\80). So, find the global <system.web> section in your web.config and make changes so that the result would look like the following:

<system.web>
  <webServices>
    <protocols>
      <add name="HttpGet" />
      <add name="HttpPost" />
    </protocols>
  </webServices>
...
</system.web>

However, from the security point of view such solution is not ideal as it allows external access through the HTTP-GET and HTTP-POST messaging protocols to all your XML web services. So, it’s better to specify the access protocols for each web service separately, not affecting other ones. The <location> element added to the root <configuration> element provides us with this capability. The sample below defines the protocols for accessing the web service reachable by the specified path:

<configuration>
...
  <location path="_layouts/Services/Products.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
    </system.web>
  </location>
...
</configuration>

Note that the _layouts virtual directory is available as a subfolder of every SharePoint Web site. So if you want to limit the use of the web service by only one SharePoint Web site, specify the path like someapp/_layouts/Services/Products.asmx.

PS Here is a good article about how to create a custom web service in SharePoint 2010.

SharePoint: How to close a Modal Dialog Window

September 18th, 2012 Admin 4 comments

    How to create/open a Modal Dialog Window (along with the passing parameters into it) is shown in the post SharePoint: How to pass parameters into a Modal Dialog Window and then access them. This post, in turn, will be devoted to closing the Modal Dialog Window.


Modal Dialog Window is based on IFrame element

As you probably know, Modal Dialog Windows are implemented through IFrame elements. So, when saying “open a web page in a Modal Dialog Window” we mean to load another Html document into an IFrame element of the current Html document. Let’s call the page, which hosts the IFrame element, a Parent-page and the page loaded into the IFrame – a Child-page. From the Child-page the IFrame element containing it can be reached by means of the window.frameElement DOM-object.


Methods to close Modal Dialog Window

To close a Modal Dialog Window we can employ the methods shown below. Note that the methods become accessible through the window.frameElement after the dialog has been opened/created, in other words, SP Dialog framework extends the window.frameElement object by adding these custom methods.


SP.UI.ModalDialog.commonModalDialogClose

This method allows to close the current (the most recently opened) Modal Dialog Window, passing a desirable DialogResult and a return value into the dialogReturnValueCallback method. This method is mostly intended to be called from the Parent-page. Below is a sample of possible use. Let’s assume that within the Parent-page we have two JavaScript functions, OpenChildDialog and CloseChildDialog, and a Html link, which opens the dialog and sets up the delayed closing of it. The functions:

function OpenChildDialog() {
  var opt = {
    url : 'childPage.aspx',

    dialogReturnValueCallback:
      function (res, retVal) {
        alert(retVal);
      }
  };
  SP.UI.ModalDialog.showModalDialog(opt);
}
function CloseChildDialog() {
  //SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Closed with OK result');
  SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel,'Cancelled');
}

The link:

<a href="#" onclick="OpenChildDialog(); setTimeout(function(){ CloseChildDialog(); }, 10000); return false;">
Open dialog
</a>

So, clicking on the link you open the dialog, which will be closed automatically in 10 seconds unless you close it manually before.


window.frameElement.commonModalDialogClose

Technically, it’s the same commonModalDialogClose function, but accessible through the window.frameElement object. Unlike the previous one the given function is intended to be called from within the Child-page (opened in the dialog). The main advantage of the window.frameElement.commonModalDialogClose is that it can be invoked from within a SharePoint-independent page, which knows nothing about SP Dialog framework and its js-files. Before showing an example, let’s take a look at the SP.UI.DialogResult enumeration, which is situated in the SP.UI.Dialog.js file:

SP.UI.DialogResult.prototype = {
    invalid: -1,
    cancel : 0,
    OK     : 1
}

Use of SP.UI.DialogResult inside the SharePoint-independent page will cause getting of ‘SP’ is undefined error message. So, we have to use the real values of SP.UI.DialogResult as the enumeration apparently will be undefined. So, below is an example of use. Let’s assume that to open the dialog we use the same OpenChildDialog method listed above and, somewhere within the Child-page, we have two Html links to close the dialog with OK or cancel as the result. The links:

<a href="#" onclick="window.frameElement.commonModalDialogClose(1 /*OK*/, 'Closed with OK result'); return false;">
Commit
</a>
<a href="#" onclick="window.frameElement.commonModalDialogClose(0 /*cancel*/, 'Cancelled'); return false;">
Cancel
</a>


window.frameElement.commitPopup

The given function closes the dialog and passes SP.UI.DialogResult.OK as the result. It also allows to pass a return value into the dialogReturnValueCallback method. Like the previous one, window.frameElement.commitPopup is intended to be called from within the Child-page, which may be SharePoint-independent. Traditionally, an example implies that the dialog is opened by the OpenChildDialog method and contains a Html link:

<a href="#" onclick="window.frameElement.commitPopup('Closed with OK result'); return false;">
Commit
</a>

Another good example of use of window.frameElement.commitPopup is demonstrated in the article – SharePoint: SPLongOperation inside a Modal Dialog Window.


window.frameElement.cancelPopUp

The window.frameElement.cancelPopUp closes the dialog as well. However, as opposite to commitPopup, it returns the SP.UI.DialogResult.cancel as the dialog result and doesn’t allow to pass a return value. It should be called from within the Child-page, which may be SharePoint-independent. The opened dialog can be closed, for example, by the Html link, which is placed within the Child-page and defined as the following:

<a href="#" onclick="window.frameElement.cancelPopUp(); return false;">
Cancel
</a>


Summary

Let’s take a look at a summary table below. The SharePointless column indicates whether the appropriate function can be used from within a SharePoint-independent page. The Intended to be placed within column shows where the appropriate function should be put in, in either Parent- or Child-pages. Note that there are no strict rules where the functions must be used, all of them, in some conditions, can be used on any pages.

Function & Description SharePointless Intended to be placed within
SP.UI.ModalDialog.commonModalDialogClose

Closes the most recently opened Modal Dialog Window, passes a DialogResult and a return value into the dialogReturnValueCallback.

NO Parent-page
window.frameElement.commonModalDialogClose

Closes the most recently opened Modal Dialog Window, passes a DialogResult and a return value into the dialogReturnValueCallback.

YES Child-page
window.frameElement.commitPopup

Closes the dialog, passes SP.UI.DialogResult.OK as the result and a return value into the dialogReturnValueCallback.

YES Child-page
window.frameElement.cancelPopUp

Closes the dialog and passes SP.UI.DialogResult.cancel as the result.

YES Child-page

ASP.NET: How to trigger a validator on the client-side

August 27th, 2012 Admin No comments


ValidatorValidate

The easiest way to trigger a validator on the client-side is to use the ValidatorValidate method provided by ASP.NET as a part of a Validation client-side API. You don’t need to include any js-files so as the all required scripts will be included automatically when you add a validator to your page. The typical use is something like this

var validator = document.getElementById('ctl00_PlaceHolderMain_info_textbox').Validators[0]; // Page_Validators[0];

ValidatorValidate(validator); // fire validation
ValidatorUpdateIsValid(); // update the global Page_IsValid flag

The ValidatorValidate makes the passed validator examine the input element bound to it and updates the validator‘s display (shows or hides its error message). I also recommend to call the ValidatorUpdateIsValid method, which updates the global variable Page_IsValid and by that may prevent the Html-form submit when the validator failed.

Below is a simple JavaScript function I use to force validation of a specified input. The function gets the input by the passed id, then goes through the all validators linked to the input and activates each of them. Finally, it updates the global Page_IsValid flag.

function ForceInputValidation(inputId) {
    var targetedControl = document.getElementById(inputId);    

    if (typeof(targetedControl.Validators) != "undefined") {
        var i;
        for (i = 0; i < targetedControl.Validators.length; i++)
            ValidatorValidate(targetedControl.Validators[i]);
    }

    ValidatorUpdateIsValid();
}

ASP.Net places the initialization of validators at the end of the web page, so, it makes sense to handle the input‘s Validators-collection after the page has been loaded entirely. The following example demonstrates how to fire validation of the specified input right after the page has been loaded. jQuery is a best helper in that.

$(document).ready(function () {
    ForceInputValidation('ctl00_PlaceHolderMain_info_textbox');
});


ValidatorEnable

As some blogs and forums recommend, you can also use another built-in function – ValidatorEnable, the code of which is shown below:

function ValidatorEnable(validator, enable) {
    validator.enabled = (enable != false);
    ValidatorValidate(validator);
    ValidatorUpdateIsValid();
}
// ...
// the typical use to fire validation is
var validator = document.getElementById('ctl00_PlaceHolderMain_info_textbox').Validators[0]; // Page_Validators[0];
ValidatorEnable(validator, true);

The ValidatorEnable calls sequentially the same ValidatorValidate and ValidatorUpdateIsValid functions we use above. Thus to activate one validator you can use, with no difference, either ValidatorEnable or combination of ValidatorValidate and ValidatorUpdateIsValid. But activating several validators (like in ForceInputValidation function) I advise employing the pair of the ValidatorValidate and ValidatorUpdateIsValid functions. That is because the ValidatorUpdateIsValid loops through all validators on the page. So, for best performance we should fire the all required validators and then call ValidatorUpdateIsValid once.

ps here is good source of information about the client-side validation.