Header

Friday, 5 July 2024

React Tutorial

What is React?

React is an open-source front-end JavaScript library that's utilized for building component bassed client application

  • React is especially used for Single page application
  • It is used for handling View layer of Web Application and Mobile app.
  • React Uses JSX syntax. JSX is as syntax extension of JS that allow developers to write HTML in their JS Code
  • React uses Virtual Dom instead of Real DOM.
  • Real DOM manipulation are expensive.
  • React uses reusable UI Components to develop the view.

What is JSX?

JSX stands for JavaScript XML and it is an XML-Like extension to ECMA Script. Basically it provide the syntax for the Below Function.

React.createElement(type, props,... children)

In the below example the text inside <h1> tag is returned as JavaScript function to render function.

export default function App(){
return(
    <h1>{"Hello this is JSX code!"} </h1>
  );
 }

If you don't use JSX syntax then the respective JavaScript code should be written as below.

Functional Component

  import {createElement} from 'react';
  export default function App(){
     return createElement(
      'h1',
      {
     className:'greeting'},
      'Hello, This is a JSx Code'
    );
  }

Class Component

  class App extend React.Component{
     render(){
      return(
     <h1>"{Hello, This is a JSx Code}</h1>
    );
  }
 }

Tuesday, 2 May 2023

Read cookie using JavaScript Code

Read cookie using JavaScript Code

Today, we'll look at how to use JavaScript code to read cookies. The function readCookie, which is located below, accepts a cookie's name and returns its value.

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++)
    {
     var c = ca[i];
     while (c.charAt(0)==' ')
     {
      c = c.substring(1,c.length);
     }
    if (c.indexOf(nameEQ) == 0)
     return c.substring(nameEQ.length,c.length);
    }
  return null;
}

I will demonstrate how to generate cookies using JavaScript in the code below.

function cookieCheck(){
  var interval;
  if(readCookie("userlogTime") == null)
  {
   var cDateTime = new Date();
   var timeSet = cDateTime.getHours();
   document.cookie ="userlogTime="+timeSet;
   }
  }
The above code show how we can create cookie using javascript

Deferred in SharePoint JSON

How to use Deferred in SharePoint JSOM?

I'll demonstrate how to utilize Deferred in SharePoint Online today.
All functions in SharePoint operate asynchronously, however occasionally we must call a function after another has finished. Assuming we have two lists and must retrieve data sequentially from each, delayed is used in this scenario

Swap value of two variables without using 3rd variable

How to swap two variable without using 3rd variable?

Hi Friends.
Today we will see how we can swap value of two variable without using the third variable.
For that will perform the below steps.
Step 1. Declare both variables.
  var x=13;
  var y=21;
Step 2. Add both variable and assign to the first variable.
  x=x+y; //13+21, x =34

Step 3. Subtract second variable from first variable as it contains the sum of both variables and assign to the second variable. By doing this, second variable will hold the value of first variable value which was assign in the beginning.

  y=x-y; //34-21, y=13

Step 4. Now subtract second variable from first variable as it contains the sum of both variables and assign to the first variable. By doing this, first variable will hold the value of second variable value which was assign in the beginning.

   x=x-y; //34-13. x=21
Complete code:-
  var x=13;
  var y=21;
  x=x+y; //13+21, x =34
  y=x-y; //34-21, y=13
  x=x-y; //34-13. x=21

File upload and overwrite into the SharePoint library using JavaScript

 Hi Friends,

We will see how we can upload file into the SharPoint library and also overwrite, if the file is present into the library.

We can use the below code to upload the file into the SharePoint document library.

Also we can overwrite the file if already present into the Document library.

By default, it does not allow to overwrite the file but through the code we can set overwrite true.

set_overwrite(true);

  <script language="javascript" type="text/javascript">

        var fileInput;
        $(document).ready(function () {

                fileInput = $("#getFile");
                SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);

            });

        function registerClick() {
            //Register File Upload Click Event   
            $("#addFileButton").click(readFile);
        }

        var arrayBuffer;

        function readFile() {

            //Get File Input Control and read the file name  
            var element = document.getElementById("getFile");
            var file = element.files[0];
            var parts = element.value.split("\\");
            var fileName = parts[parts.length - 1];

            //Read File contents using file reader  

            var reader = new FileReader();
            reader.onload = function (e) {
                uploadFile(e.target.result, fileName);
            }
            reader.onerror = function (e) {
                alert(e.target.error);
            }

            reader.readAsArrayBuffer(file);
        }

        var attachmentFiles;

        function uploadFile(arrayBuffer, fileName) {
            //Get Client Context,Web and List object.  
            var clientContext = new SP.ClientContext();
            var oWeb = clientContext.get_web();
            var oList = oWeb.get_lists().getByTitle('Documents');

            //Convert the file contents into base64 data  
            var bytes = new Uint8Array(arrayBuffer);
            var i, length, out = '';
            for (i = 0, length = bytes.length; i < length; i += 1) {
                out += String.fromCharCode(bytes[i]);
            }
            var base64 = btoa(out);

            //Create FileCreationInformation object using the read file data  
            var createInfo = new SP.FileCreationInformation();
            createInfo.set_content(base64);
            createInfo.set_overwrite(true);
            createInfo.set_url(fileName);

            //Add the file to the library  

            newFile = oList.get_rootFolder().get_files().add(createInfo);
            var myListItem = newFile.get_listItemAllFields();
            myListItem.set_item("PID", "33")

            //Load client context and execcute the batch  
            myListItem.update();
            clientContext.load(newFile);
            clientContext.executeQueryAsync(QuerySuccess, QueryFailure)
        }

        function QuerySuccess() {

            console.log('File Uploaded Successfully.');
            alert("File Uploaded Successfully.")
        }

        function QueryFailure(sender, args) {

            console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
            alert("Request failed with error message - " + args.get_message() + " . Stack Trace - " + args.get_stackTrace());

        }


    </script>



Monday, 1 May 2023

How to prevent to fire parent click in jQuery/JavaScript

Hi Friends,
Today we will see how we can prevent parent click event when end user clicks on child. 

Some time it happens that we have associated click event of parent DOM element and also on click of Child DOM element. In this situation if end user clicks on Child element, then both events will be triggered. But our requirement is not firing Parent event on clicking on child element. 
<html>
    <head>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
    $(".parent").on('click',function(e){
        alert("You have called Dad");
    });
    $(".child").on('click',function(e){
          alert("You have called son");
    });
});
  </script>
    </head>
    <body>
        <div class="parent">
            <div class="child">Child where event has been added</div>
            <div>Child where no event has added </div>
        </div>
    </body>
</html>

If you run above code, it will show you two alerts on clicking on Child element. 
To resolve this issue, we will use e.stopPropagation();
This small line of code will solve the problem. 


<html>
    <head>
<script
  src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
    $(".parent").on('click',function(e){
        alert("You have called Dad");
    });
    $(".child").on('click',function(e){
        e.stopPropagation();
        alert("You have called son");
    });
});
  </script>
    </head>
    <body>
        <div class="parent">
            <div class="child">Child where event has been added</div>
            <div>Child where no event has added </div>
        </div>
    </body>
</html>











Sunday, 14 July 2013

Get Data of current login user in Sharpoint




Get Data of current login user in Sharpoint
some time we need to get data according to current user.
Like items that has been created by current login user.

And there so many approach to do this but,
what I will recommend that never goes wrong.

  osb.Append("     <Where>")
  osb.Append("       <Eq>")
  osb.Append("        <FieldRef Name=""Author"" LookupId=""True"" />")
  osb.Append("        <Value Type=""Lookup""   >" &
                        SPContext.Current.Web.CurrentUser.ID & "</Value>")
  osb.Append("      </Eq>")
  osb.Append("   </Where>")


Just add this query and get what you wanted :D