Thank you for visiting my site!

Home / REST API/jQuery / REST API – jQuery -Working with Lists

REST API – jQuery -Working with Lists

View All Lists

Source Code:

 

<h2>Add New</h2>

<div class="form-group">
        <label for="txtListAddName">Title:</label>
        <input type="text" class="form-control" id="txtListAddName" placeholder=""> 
      </div>
   
      <button onclick="onAdd();return false;" class="btn btn-outline-primary" id="btnSubmitListName">Submit</button>

      <button onclick="onAddCancel();return false;" class="btn btn-outline-secondary" id="btnCanceltListName">Cancel</button>

</div>

<div id="divEditListData" style="display:none;">
  

<h2>Edit List</h2>

<div class="form-group">
        <input type="text" class="form-control" id="txtListEditId" placeholder=""> 
        <label for="txtListEditName">Title:</label>
        <input type="text" class="form-control" id="txtListEditName" placeholder=""> 
      </div>
        
      <button type="button" onclick="onUpdate();return false;" class="btn btn-outline-primary" id="btnUpdateListName">Update</button>

      <button type="button" onclick="onEditCancel();return false;" class="btn btn-outline-secondary" id="btnEditCanceltListName">Cancel</button>

</div>

<div id="divGetListData">divGetListData</div>

<!-- Modal -->


<div class="modal fade" id="modalConfirm" tabindex="-1" role="dialog" aria-labelledby="modalConfirmLabel" aria-hidden="true">
  
<div class="modal-dialog" role="document">
    
<div class="modal-content">
      
<div class="modal-header">
        
<h5 class="modal-title" id="modalConfirmLabel">DELETE</h5>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>
      </div>

div class="modal-body"> Do you want to delete this? 
        <input type="text" name="itemListName" id="itemListName" value=""/>
      </div>

<div class="modal-footer">
        <button type="button" id="cancelItem" class="btn btn-outline-secondary" >NO</button>
        <a href="#delete" id="deleteItem" class="btn btn-outline-primary">YES</a> </div>

    </div>

  </div>

</div>

//* *****************************************************************//
//                         Show List
//* *****************************************************************//
$(function(){
    getListData();
})

function clearList(){
    var listItemInfo = '';
    $("#divGetListData").html(listItemInfo);
}

//* *****************************************************************//
//                         Get List
//* *****************************************************************//
function getListData(){
    var siteUrl = _spPageContextInfo.webAbsoluteUrl;
    var fullUrl = siteUrl + "/_api/web/lists?$filter=Created ge datetime'2019-11-12T00:00:00Z'";

    $.ajax({
        url: fullUrl,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",            
            "content-type": "application/json; odata=verbose", 
        },
        success: onQuerySucceeded,
        error: onQueryFailed
    })
}

function onQuerySucceeded(data) {
    console.log(data);
    var listItemInfo = '';
    listItemInfo += '<table class="table table-striped"><thead ><tr><th scope="col" style="display:none">Id</th><th scope="col">List Name</th><th scope="col"></th><th scope="col"></th></tr></thead><tbody>';

    $.each(data.d.results, function(key, value){
        listItemInfo += '<tr>';
        
        listItemInfo += '<th style="display:none">'+ value.Id;  '</th>';
        listItemInfo += '<td> ' + value.Title + '</td>'; 

        listItemInfo += '<td> <button class="btn btn-outline-primary" id="btnEditThisList"'; 
        listItemInfo += 'onclick="onEdit(\''+ value.Id +'\');return false;" >Edit</button>' + '</td>';

        listItemInfo += '<td> <button type="button" class="btn btn-outline-danger" id="btnDeleteThisList"'; 
        listItemInfo += 'onclick="onDelete(\''+ value.Title +'\');return false;" >Delete</button>' + '</td>';

        listItemInfo += '</tr>';
    });

    listItemInfo +='</tbody></table>';
    
    $("#divGetListData").html(listItemInfo);
}

//* *****************************************************************//
//                          Modal Confirm delete
//* *****************************************************************//

var listname = '';

function onDelete(listName) {
    listname = listName;
    $('#itemListName').val("");
    $('#itemListName').val(listname );
    //console.log('listname ' + listname);
    $('#modalConfirm').modal('show');
}

$( document ).on( "click", "#deleteItem", function() {
     //console.log('deleteItem ' + listname);
     deleteList(listname);
     clearList();
     getListData();
     listname = '';
     $('#itemListName').val(listname );
     $('#modalConfirm').modal('hide');
});

$( document ).on( "click", "#cancelItem", function() {
    listname = '';
    $('#itemListName').val(listname );
    //console.log('cancelItem ' + listname);
    $('#modalConfirm').modal('hide');
});

//* *****************************************************************//
//                          Add New List
//* *****************************************************************//

function onAdd() {          
    var listName = $("#txtListAddName").val();        
    createList(listName);    
}

function onAddCancel(){
    console.log("onAddCancel");
    clearAddForm();
}

function clearAddForm(){
    $("#txtListAddName").val("");
}

function createList(listName) {    
    var siteUrl = _spPageContextInfo.webAbsoluteUrl;    
    var fullUrl = siteUrl + "/_api/web/lists";
 
    $.ajax({        
        url: fullUrl,        
        type: "POST",        
        data: JSON.stringify({            
            '__metadata': { 'type': 'SP.List' },            
            'BaseTemplate': 100,            
            'Title': listName        
        }),        
        headers: {            
            "accept": "application/json;odata=verbose",            
            "content-type": "application/json;odata=verbose",            
            "X-RequestDigest": $("#__REQUESTDIGEST").val()        
        },        
            
        success: onQueryAddNewSucceeded,        
        error: onQueryFailed    
    }); 
}
 
function onQueryAddNewSucceeded(data) { 
    clearAddForm();
    clearList();
    getListData();
}
 
//* *****************************************************************//
//                          Edit List
//* *****************************************************************//

function onAddNew() {
    clearEditForm();

    $("#divAddListData").css('display','inline' );
    clearAddForm();
    $("#divEditListData").css('display', 'none');
}

function onEdit(id) {
    
    //hide add form, clear fields,
    $("#divAddListData").css('display', 'none');
    clearAddForm();
    $("#divEditListData").css('display', 'inline');

    getListDataById(id);
}

function getListDataById(id){
    var siteUrl = _spPageContextInfo.webAbsoluteUrl;
    var fullUrl = siteUrl + "/_api/web/lists/getById('"+id+"')";
    
    $.ajax({
        url: fullUrl,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",            
            "content-type": "application/json;odata=verbose", 
        },
        
        success: onQueryGetListByIdSucceeded,
        error: onQueryFailed
    })
}

function onQueryGetListByIdSucceeded(data) { 
    //var response= JSON.stringify(data);
    //console.log(' onQueryGetListByIdSucceeded: ' + response);
    //console.log(' Title data: ' + data.d.Title);
    clearEditForm();
    fillEditForm(data);
}

function clearEditForm(){
    
        $("#txtListEditId").val("");
        $("#txtListEditName").val("");
}

function fillEditForm(data){
   
    var listId = data.d.Id;
    var listName = data.d.Title;

    $("#txtListEditId").val(listId);
    $("#txtListEditName").val(listName);
}

function onEditCancel(){
    clearEditForm();
    $("#divEditListData").css('display', 'none');
    $("#divAddListData").css('display', 'inline');
    clearAddForm();
} 

function onUpdate(){
    UpdateList();
}

function UpdateList()  { 
   
    var listId = $("#txtListEditId").val();  
    var listName = $("#txtListEditName").val(); 

    var siteUrl = _spPageContextInfo.webAbsoluteUrl;    
    var fullUrl = siteUrl + "/_api/web/lists/getById('"+ listId +"')"; 
    console.log(fullUrl);        
    console.log(listId); 
    console.log(listName); 
                      

    $.ajax({
        url:  fullUrl,
        type: "POST",
        headers: {
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(), // <-- digest
            "X-HTTP-Method": "MERGE", // <-- for update request
            "IF-MATCH": "*" // <-- for update request
        },

        data: JSON.stringify({            
        '__metadata': { 'type': 'SP.List' },            
        'BaseTemplate': 100,            
        'Title': listName
        //,'Id':listId       
        }),
        success: onQueryListUpdatedSucceeded,
        error: onQueryFailed
    }); 
} 
 
function onQueryListUpdatedSucceeded(){
    clearEditForm();
    //hide add form, clear fields,
    $("#divAddListData").css('display', 'inline');
    clearAddForm();
    $("#divEditListData").css('display', 'none');
    clearList();
    getListData();
}

//* *****************************************************************//
//                          Delete
//* *****************************************************************//

// occurs when a user clicks the delete button
/* function onDelete(listName) {
    var x = confirm("Are you sure you want to delete?");
    if (x){
        deleteList(listName);
    }
    else
      return false;
} */

function deleteList(listName) {
    var siteUrl = _spPageContextInfo.webAbsoluteUrl;    
    var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('"+ listName + "')";
    $.ajax({        
        url: fullUrl,        
        type: "DELETE",        
        headers: {            
            "accept": "application/json;odata=verbose",            
            "content-type": "application/json;odata=verbose",            
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),                    
            "IF-MATCH": "*"        
        },        
        success: onDeleteSucceeded,        
        error: onQueryFailed    
    }); 
}

function onDeleteSucceeded() {  
    clearList();
    getListData();
} 

function onQueryFailed(jqXhr, textStatus, errorMessage) {
    //alert(JSON.stringify(error));
    console.log('errorMessage: ' + errorMessage);
    console.log('jqXhr: ' + jqXhr );
    console.log('textStatus: ' + textStatus);  
}

ADD YOUR COMMENT