Thursday, May 14, 2020

How to swap two variable values without using third variable?

Ans:- int a=10, b=20;      
     
a=a+b;   //a=30 (10+20)    
b=a-b;   //b=10 (30-20)    
a=a-b;   //a=20 (30-10) 

now a=20, b=10

Onload () or document.ready () which will load first and why?

Ans:- The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

What is synchronous and Asynchronous call?

Ans:-
Ajax:- It is a technique that incorporates a client-side script (i.e. a script that runs in a user's browser) that communicates with a web server. An AJAX application might use XML to send data, it could also use just plain text or JSON text. 
By default, the$.ajaxrequest in jQuery is set to asynchronous. The variable name is async and the value is set to true

Synchronous ( async: false ) – In case of Synchronous AJAX request, the request is sent to the server and the client waits for the server’s response before it executes the script further. So this is the special case when the further script is dependent on the results returned by the server.

Asynchronous ( async: true ) - In an Asynchronous request the process is handled independently and is not dependent on following processes. So that the script do not wait for the server request to complete before executing the remaining lines of code. As soon as the server response is completed it is sent back to the client.

$.ajax({
         url: <siteUrl>,
         type: "POST",
         async: false,
         success: function(data) {
                // .....
         }
      });

What is REST API in SharePoint?

Ans:- REST is an architectural style (general and reusable solution) providing standards between computer systems on the web, making them easier to communicate with each other.

SharePoint REST API is an interface which allows communication between the SharePoint server and client machine.

Using SharePoint REST APIs, users can interact remotely with SharePoint data by using any technology that supports REST web requests.

How we can get the lookup column value using rest API?

Ans:- We can get the value of lookup column by using $expand keyword.

var Url=_spPageContextInfo.siteAbsoluteUrl+"/_api/web/lists(guid'<guid>')/items?$select=Id,Title,LookupField1/FieldToBeExpanded1,LookupField2/FieldToBeExpanded2&$expand=LookupField1,LookupField2"

When creating a lookup field, you can select which field from source list you want to show. The number of such fields is limited by field type. For example, you can create a lookup with lookup field pointed only to the following field types:

Single line of text
Date and Time
Number

Thus in your REST query, you can select additional fields only with above-mentioned field types. For example, you have a list Category with fields Title, Id, Active (custom Yes\No field). You created a lookup to Category in your other list (employee).
/_api/web/lists/getbytitle('employee')/items?$select=category/Id,category/Title&$expand=category - works

and

/_api/web/lists/getbytitle('employee')/items?$select=category/Id,category/Title,category/Active&$expand=category - doesn't work because Yes\No is unsupported field type for lookup.

Can we use CAML query in Rest Api. If yes then how?

Ans:- Yes we can use CAML query with Rest Api. In some terms, when you needed to do some complicated query in a SP list. To do these queries you can prefer CAML.

It always has to be a POST request. The request header is the same as the other normal post requests for SharePoint Rest API.
headers: {
         "X-RequestDigest": $("#__REQUESTDIGEST").val(),
         'content-type': 'application/json;odata=verbose',
         'accept': 'application/json;odata=verbose'
}

The REST endpoint for using CAML query is:
/_api/web/lists/GetByTitle('<List Name>')/GetItems

The complete code with the REST call is given below:
// Include JQuery reference
// ... script continues ...
        /// List Name and CAML Query as Parameter
        function restCallwithCaml(listName, caml) {
             /// get the site url
             var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
             /// set request data     
             var data = { "query" : {"__metadata": { "type": "SP.CamlQuery" }, 
                                                      "ViewXml":caml}
                               };
             /// make an ajax call
             $.ajax({
                url: siteUrl+"/_api/web/lists/GetByTitle
                ('"+ listName +"')/GetItems",
                method: "POST",
                data: data,
                headers: {
                   "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                   'content-type': 'application/json;odata=verbose',
                   'accept': 'application/json;odata=verbose'
                }
                success: function (response) {
                    ///do your code
                },
                error: function (data) {
                  ///do your code
                }
            });
       }
The CAML Query has to use in between this <View><Query>…CAML Query…</Query></View> tag. The query with the way to call the function is given below:

var caml = "<View><Query><Where><Eq><FieldRef Name='EndDate' /><Value Type='DateTime'><Today /></Value></Eq></Where></View></Query>";

restCallwithCaml(<listName>, caml);

Create,Read,Update and Delete (CRUD) operations using Rest Api in SharePoint?

Ans:-
Get List Items
In order to get all items from the list, below code can be used-
$.ajax({
        var siteurl = _spPageContextInfo.webAbsoluteUrl;
        $.ajax({
                   url: siteurl + "/_api/web/lists/getbytitle('Projects')/items",
                   type: "GET",
                   headers: { 
                        "Accept": "application/json; odata=verbose" 
                       },
                   success: function (data) {
                        if (data.d.results.length > 0 ) {
                             //This section can be used to iterate through data and show it on screen
                        }       
                  },
                  error: function (data) {
                      alert("Error: "+ data);
                 }
          });
    });

Add New List Item
In order to add new list item, we have to create a data variable and assign values to the fields, then perform a 'POST' request. See below code-
var data = {
            __metadata: { 'type': 'SP.Data.ProjectsListItem' },
           Title: 'Please provide title here',
           Description: 'Please provide multi line text here',
           Start_x0020_Date: new Date().toISOString();
      };
    $.ajax({
        var siteurl = _spPageContextInfo.webAbsoluteUrl;
        $.ajax({
                   url: siteurl + "/_api/web/lists/getbytitle('Projects')/items",
                   type: "POST",
                   data: JSON.stringify(data),
                   headers: { 
                         "Accept": "application/json; odata=verbose",
                          "Content-Type": "application/json; odata=verbose",
                         "X-RequestDigest": $("#__REQUESTDIGEST").val()                                  
                   },
                   success: function (data) {
                              alert('Item added successfully');
                  },
                  error: function (error) {
                      alert("Error: "+ JSON.stringify(error));
                 }
          });
    });

Update List Item
In order to update a list item, we have to pass Item Id in Url, create data variable and use one of the HTTP methods - MERGE, PATCH or PUT. Preferred or recommended methods are PATCH or MERGE a PUT requires all fields to be sent as an object.

This is similar to adding a new item with few minor changes.
var data = {
            __metadata: { 'type': 'SP.Data.ProjectsListItem' },
           Title: 'Please provide title here',
           Description: 'Please provide multi line text here',
           Start_x0020_Date: new Date().toISOString();
      };
    $.ajax({
        var siteurl = _spPageContextInfo.webAbsoluteUrl;
        $.ajax({
                   url: siteurl + "/_api/web/lists/getbytitle('Projects')/items/getbyId(3)",
                   type: "POST",
                   data: JSON.stringify(data),
                   headers: { 
                               "accept":"application/json;odata=verbose",
"content-Type":"application/json;odata=verbose",
                                "X-RequestDigest":$('#__REQUESTDIGEST').val(),
"X-HTTP-Method":"MERGE",
"IF-Match":"*",                              
                   },
                   success: function (data) {
                              alert('Item updated successfully');
                  },
                  error: function (error) {
                      alert("Error: "+ JSON.stringify(error));
                 }
          });
    });

Delete Specific List Item
In order to delete a specific item from the list, we have to make few changes and do some addition to the code. See below code-
 $.ajax({
        var siteurl = _spPageContextInfo.webAbsoluteUrl;
        $.ajax({
                   url: siteurl + "/_api/web/lists/getbytitle('Projects')/items/getbyId(1)",
                   type: "POST",
                   headers: { 
                                "accept":"application/json;odata=verbose",
"content-Type":"application/json;odata=verbose",
"X-RequestDigest":$('#__REQUESTDIGEST').val(),
"X-HTTP-Method":"DELETE",
"If-Match":"*",
                   },
                   success: function (data) {
                              alert('Item deleted successfully');
                  },
                  error: function (error) {
                      alert("Error: "+ JSON.stringify(error));
                 }
          });
    });