Friday, January 30, 2015

How to get the value from the URL parameter?

Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).
It's awesome because it:
  • Is recursive
  • Handles multiple parameters of the same name
  • Deals well with malformed parameter strings (missing values, so on)
  • Doesn't break if '=' is in the value
  • Performs URL decoding
  • IS RECURSIVE!
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,  
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }
var fType = getUrlVars()["type"];

Window Location

Window Location

The window.location object can be written without the window prefix.
Some examples:
  • window.location.href returns the href (URL) of the current page
  • window.location.hostname returns the domain name of the web host
  • window.location.pathname returns the path and filename of the current page
  • window.location.protocol returns the web protocol used (http:// or https://)
  • window.location.assign loads a new document

Window Location Href

The window.location.href property returns the URL of the current page.

Example

Display the href (URL) of the current page:
"Page location is " + window.location.href;
Result is:
Page location is http://XXXX 

Window Location Hostname

The window.location.hostname property returns the name of the internet host (of the current page).

Example

Display the name of the host:
"Page host is " + window.location.hostname;
Result is:
Page hostname is www.Test.com

Window Location Pathname

The window.location.pathname property returns the path name of page.

Example

Display the path name of the current URL:
"Page path is " + window.location.pathname;
Result is:
/js/js_window_location.asp

How to Reload the Page With JavaScript

There are several ways to reload the current page using a button or other trigger. The examples below use a button click to reload the page but you can use a text hyperlink or any trigger you like.
<input type="button" value="Reload Page" onClick="window.location.reload()">


<input type="button" value="Reload Page" onClick="history.go(0)">


<input type="button" value="Reload Page" onClick="window.location.href=window.location.href">

Required URL to Open in Model Popup

Here’s what the URL may look like:
1
/sites/lozzi/Lists/Events/DispForm.aspx?ID=4&IsDlg=1
Note the IsDlg=1 at the end. I’m a big fan in questioning everything, so let’s try it out for ourselves.
Go to a display form of a list item, which is not in a dialog.
A Normal Display Form
and add &IsDlg=1 (case sensitive) to the end of the URL, hit enter.
Display Form with IsDlg=1

Thursday, January 29, 2015

Deleting Multiple items using ECMA Script

In this post we will see how to Delete multiple items from SharePoint list items with ECMAScript (aka javascript client object model)

Delete multiple item from SharePoint list.
The following example can help you to understand the request/response model. The following code snippet uses JSOM to retrieve an item based on its ID. It returns the current client context and then calls the executeQueryASync method, specifying the callback methods for success and failure of the operation

function DeleteCrossChargeTransactions(vReferenceId)
{
    try
        {
           
            var contextDelete = new SP.ClientContext.get_current();
            var webDelete = contextDelete.get_web();
            var listDelete = webDelete.get_lists().getByTitle('XXX');
            var queryDelete = new SP.CamlQuery();
           
            queryDelete.rowLimit=100;
            queryDelete.set_viewXml('<View Scope=\'RecursiveAll\'><Query><Where><Eq><FieldRef Name="Reference_x0020_Id" /><Value Type="Text">'+vReferenceId+'</Value></Eq></Where></Query></View>');
            // add your query to the getItems command for your list
           this.collListItemsDelete = listDelete.getItems(queryDelete);
           
             // issue the load command, these can be batched for multiple operations
             contextDelete.load(collListItemsDelete);
             // execute the actual query against the server, and pass the objects we have created to either a success or failure function
             contextDelete.executeQueryAsync(Function.createDelegate(this, this.SuccessFunction), Function.createDelegate(this, this.failed));
                                    
        }
    catch(e)
        {
           
        }
}
function SuccessFunction()
{
    var itemsToDelete = new Array();
    var count = this.collListItemsDelete.get_count();
   var listEnumerator = this.collListItemsDelete.getEnumerator();
   var contextDelete= new SP.ClientContext.get_current();
    while (listEnumerator.moveNext()) {
       var item = listEnumerator.get_current();
       itemsToDelete.push(item);
   }    
   for (var i = itemsToDelete.length-1; i >= 0 ; i--) {
       itemsToDelete[i].deleteObject();
   }
   contextDelete.executeQueryAsync(Function.createDelegate(this, this.allItemsDeleted), Function.createDelegate(this, this.failed));
   
}

Opening and Closing Modal SP Dialog


Opening and closing SharePoint modal dialogs has been blogged to death already so here are a few resources for that:
The first thing that I wanted to point out is the SP.UI.ModalDialog.RefreshPage method. If dialog requires updating information on the parent page, which you may not have access to, you can use this method to force a page refresh if the dialog returns a success value. An example of this is when your dialog results in column values being updated on a SP list view.
      function myShowDialog() {
           var options = {
               url: LocationURL,
               dialogReturnValueCallback: feedbackReceived,
               title: "Add Follow Records"
           };
           SP.UI.ModalDialog.showModalDialog(options);
       }
         
       function feedbackReceived(dialogResult, returnValue) {
           if (dialogResult == SP.UI.DialogResult.OK) {
               location.href = location.href;
           } else {
               return false;
           }
SP.UI.ModalDialog.RefreshPage(dialogResult);
       }

Retrieve List Items Using ECMA

The getItems(query) function enables you to define a Collaborative Application Markup Language (CAML) query that specifies which items to return. You can pass an undefined CamlQuery object to return all items from the list, or use the set_viewXml function to define a CAML query and return items that meet specific criteria.

The following example displays the ID, in addition to the Title and Body column values, of the first 100 items in the Announcements list, starting with list items whose collection ID is greater than 1.

    <script type="text/javascript">

        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
        // It will execute after SP.ClientContext is loaded
        function retrieveListItems() {
            var clientContext = new SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('Test Data');
            var camlQuery = new SP.CamlQuery(); camlQuery.set_viewXml('<View/>');
            this.collListItem = oList.getItems(camlQuery); clientContext.load(collListItem);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
        function onQuerySucceeded(sender, args) {
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current(); oListItem.get_item('YTD');
            }
        }


    </script>