How to call one function inside second in jQuery/JavaScript

Let’s consider you have a function named makeAddition() as follows:

makeAddition(a,b){
   var c = a+b;
   alert("Addition: "+ c);
}

Now if you have another function named makeSubtraction() as follows:

makeSubtraction(a,b){
   var d = a-b;
   alert ("Subtraction: "+ d);
}

You can call makeAddition function inside makeSubtraction function as follows:

makeSubtraction(a,b){
   var d = a-b;
   alert ("Subtraction: "+ d);
   makeAddition (4,5);
}

Now when you call makeSubtraction (10,5), it will first alert answer as 5 and then it will call makeAddition function and will alert answer as 9.

Convert Excel to JSON using JavaScript code

Hello friends, in this javascript tutorial we are going to learn about how to Convert Excel to JSON using JavaScript code. We can read an excel file which is hosted on any server, SharePoint folder, etc with the help of javascript code. Here you can get readymade javascript code for Excel to JSON conversion.

Excel to JSON
Excel to JSON

Convert Excel to JSON using JavaScript Code

In this tutorial, we are going to use a js-xlsx library to convert Excel to JSON. It has xlsx.full.min.js file which we are going to refer in our HTML file. js-xlsx is a parser and writer for various spreadsheet formats. So without wasting time lets jump to coding part. We can also use .csv files as well.

Below is a code for reading Excel as a JSON object:

<!doctype html>
<html>

<head>
    <title>Excel to JSON Demo</title>
    <script src="xlsx.full.min.js"></script>
</head>

<body>

    <script>
        /* set up XMLHttpRequest */
        var url = "https://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
        var oReq = new XMLHttpRequest();
        oReq.open("GET", url, true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function(e) {
            var arraybuffer = oReq.response;

            /* convert data to binary string */
            var data = new Uint8Array(arraybuffer);
            var arr = new Array();
            for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            var bstr = arr.join("");

            /* Call XLSX */
            var workbook = XLSX.read(bstr, {
                type: "binary"
            });

            /* DO SOMETHING WITH workbook HERE */
            var first_sheet_name = workbook.SheetNames[0];
            /* Get worksheet */
            var worksheet = workbook.Sheets[first_sheet_name];
            console.log(XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            }));
        }

        oReq.send();
    </script>
</body>

</html>

In the above code, if you could observe, you will find that we have used xlsx.full.min.js file and a Test.xlsx file. We are going to read Test.xlsx Excel file to generate a JSON Object.

Note: While using above code make sure that you have uploaded your Excel file on any server and give the correct full path of that file. You can use the same code to convert CSV to JSON.

Here is our Test.xlsx file which looks like below

Output

When you host your index.html file on the server, on the page load we are running our script to show the objects in the browser console. Below is the output in JSON object

JSON Object output
JSON Object output

Download Excel to JSON javascript

You can use any one of the links to download the source code

  1. MyClassBook: Download
  2. Google Drive: Download
  3. MediaFire: Download

I hope you liked this article. Please let us know if you face any issues in the comment sections below. Like our facebook page and subscribe to our newsletter for future updates. Have a great time! 🙂

How to Display SharePoint List in jQuery Datatables

Hello friends, in this article we are going to retrieve data from SharePoint List using REST API and will display that data into jQuery Datatable. So let’s begin…

Show SharePoint List in Datatable format

Step 1:

We have a SharePoint list named EmployeeDetails as shown below with some dummy data. This list has 4 columns (Title, Name, Salary, Address).

EmployeeDetails List
EmployeeDetails List

Step 2 : Create a site page where we are going to show above data in datatable. For creating a page go to Site contents > Site pages > Click on new page icon. In this case I have created a page with name Employee Details.

Step 3 : Insert a Content Editor Webpart into a page.

Employee Details Page
Employee Details Page

Step 4 : Edit the Content Editor Webpart and paste the below code into it.

 

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../SiteAssets/EmployeeJqueryDatatable.js"></script>
<div id="DatatablePanel">
    <table style="width: 100%;">
        <tr>
            <td>
                <div id="DatatableGrid" style="width: 100%"></div>
            </td>
        </tr>
    </table>
</div>

download above html file here. (or you can use MediaFire link)

Step 5 : If you can observe the above code, we have referenced a .js file named EmployeeJqueryDatatable.js So we have to first create this js file and upload it into Site assets. Please copy the below code into this js file and named it as EmployeeJqueryDatatable.js

$(document).ready(function() {
    var RestUrl = "../_vti_bin/listdata.svc/EmployeeDetails";
    $.ajax({
        url: RestUrl,
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            if (data.d.results.length > 0) {
                //construct HTML Table from the JSON Data
                $('#DatatableGrid').append(GenerateTableFromJson(data.d.results));
                //Bind the HTML data with Jquery DataTable
                var oTable = $('#EmployeeTable').dataTable({
                    "iDisplayLength": 5,
                    "aLengthMenu": [
                        [5, 10, 30, 50],
                        [5, 10, 30, 50]
                    ],
                    "sPaginationType": "full_numbers"
                });
            } else {
                $('#DatatableGrid').append("<span>No Employee Details Found.</span>");
            }
        },
        error: function(data) {
            $('#DatatableGrid').append("<span>Error Retreiving Employee Details. Error : " + JSON.stringify(data) + "</span>");
        }
    });

    function GenerateTableFromJson(objArray) {
        var tableContent = '<table id="EmployeeTable" style="width:100%"><thead><tr><td>Title</td>' + '<td>Name</td>' + '<td>Salary</td>' + '<td>Address</td>' + '</tr></thead><tbody>';
        for (var i = 0; i < objArray.length; i++) {
            tableContent += '<tr>';
            tableContent += '<td>' + objArray[i].Title + '</td>';
            tableContent += '<td>' + objArray[i].Name + '</td>';
            tableContent += '<td>' + objArray[i].Salary + '</td>';
            tableContent += '<td>' + objArray[i].Address + '</td>';
            tableContent += '</tr>';
        }
        return tableContent;
    }
});

download above .js file here (for security reasons I have used .txt file here, so after downloading rename it to .js) or you can use MediaFire link to download the direct js file here

Step 6 : Once you upload the above js file into your site assets, go to our EmployeeDetails page that we ceated in step no. 2. Here we go!!! below is the output for our EmployeeDetails list

Video tutorial:

I have also created a step by step video tutorial for SharePoint Datatables. Please watch it for clear understanding:

https://www.youtube.com/watch?v=gXoeBrXSb3A

I would like to reply to your queries. Please let me know whether you liked this simple step by step article on SharePoint Datatable integration. I am waiting for your comments! Please like our facebook page and subscibe to our newsletter for future updates. Have a nice day!

Load Different JavaScript for Different Browsers

Hi friends, in this article we are going to learn how we can load different JavaScript for different browsers. A few days ago I was trying to implement back button in one of my HTML pages. The page on which I was trying to implement Back button was loading from one of the auto-redirected pages.

So this back button was working on Chrome browser but not on Internet Explorer. Chrome is enough intelligent browser and it can detect that the page is from one redirected page. So when we click on the back button it will land you to 2 pages back. But Internet Explorer cant has this intelligence.

When I was trying to click on the Back button in Internet Explorer, it was loading the previous page. As the previous page was having auto-redirect code so it again goes to the same page which was having Back button. So using Back button in Internet Explorer was producing a never-ending loop. So I thought to implement one trick which will load 2 page back button in IE. This can be implemented by loading Browser specific JavaScript. Using this method we can load different JavaScript for different browsers.

Browser Specific JavaScript

Here we are using Back button which will call goBack() onclick event.

 <input type="button" onclick="goBack()" value="BACK" />  

We all know that we use window.history.go(-1); for loading previous page. But we need window.history.go(-2); to load in Internet Explorer. We can use the following code which will load these actions depending on which browsers you are using.

 <script>  
      function goBack() {  
       // Internet Explorer 6-11  
       var isIE = /*@[email protected]*/false || !!document.documentMode;  
       if(isIE)  
       {  
         window.history.go(-2);  
       }  
       else  
       {  
         window.history.go(-1);  
       }  
      }  
 </script>  

This script can be used to load window.history.go(-2); for IE browser and window.history.go(-1); for browsers other than IE.

If you like this article, please share it with your friends and like our facebook page for future updates. Subscribe to our newsletter to get notifications about our updates via email. If you have any queries, feel free to ask in the comments section below. Have a nice day!