Combining code to create a table and transfer files with the help of Rest API and Javascript

I have successfully implemented a code that draws a table using CEWP SPO. Now, I am looking to enhance this functionality by adding a button to each row in the table. This button should be able to move the corresponding files from their current location to another document library within the same SPO site. The file names are retrieved using FileLeafRef.

To achieve this, I need to merge two functions. The data is currently being pulled using Ajax GET and the move command requires a POST type. I require assistance in merging these functions to achieve the desired outcome.

Current Code:


$(function(){
        var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('List_Name')/items?$top=10&$orderby=Created%20desc&$select=Reg,NBR,Date";
           $.ajax({
              url: requestUri,
              type: "GET",
              headers: {
                  "accept":"application/json; odata=verbose"
              },
              success: onSuccess,
});
  function onSuccess(data) {
     var objItems = data.d.results;
     var tableContent = '<table id="Table"><tr><th>Reg</th><th>Num</th><th>Date</th></tr>';
     for (var i = 0; i < objItems.length; i++) {
         tableContent += '<tr>';
         tableContent += '<td>' + objItems[i].Reg + '</td>';
         tableContent += '<td>' + objItems[i].NBR + '</td>';
         tableContent += '<td>' + moment(objItems[i].Date).format("DD-MM-YYYY") + '</td>';       
         tableContent += '</tr>';
 }
   $('#Grid').append(tableContent);
   }
});

Move File Code:


function MoveFile(){
        var oUrl =  _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfilebyserverrelativeurl('/Lib1/doc.docx')/moveto(newurl='/Lib2/doc.docx',flags=1)";
        $.ajax({
            url: oUrl,
            type: "POST",
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest":  $("#__REQUESTDIGEST").val()
            },
            success: function(data){
                console.log(data);
            },
            error: function(data){
                console.log(data);
            }
        });
    }

Answer №1

Below is the code after merging:

<script>


    $(function () {
        var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Documents')/items?$top=10&$orderby=Created desc&$select=*,FileLeafRef";
        $.ajax({
            url: requestUri,
            type: "GET",
            headers: {
                "accept": "application/json; odata=verbose"
            },
            success: onSuccess,
        });
        function onSuccess(data) {
            var objItems = data.d.results;
            console.log(objItems)
            var tableContent = '<table id="Table" style="width:100%"><tr><th>ID</th><th>Title</th><th>Date</th></tr>';

            for (var i = 0; i < objItems.length; i++) {
                if (objItems[i].FileSystemObjectType != 1) {
                    var fileName=encodeURI(objItems[i].FileLeafRef);
                    var button = "<input type='button' value='MoveFile' onclick= MoveFile('"+encodeURI(objItems[i].FileLeafRef) +"')>"
                    tableContent += '<tr>';
                    tableContent += '<td>' + objItems[i].ID + '</td>';
                    tableContent += '<td>' + objItems[i].FileLeafRef + '</td>';
                    tableContent += '<td>' + moment(objItems[i].Created).format("DD-MM-YYYY") + '</td>';
                    tableContent += '<td>' + button + '</td>';
                    tableContent += '</tr>';

                }
            }
            $('#Grid').append(tableContent);
        }
    });

    function MoveFile(FileLeafRef) {
        var sourceFile = "/sites/NewProvision/Shared Documents/" + FileLeafRef;
        var targetFile = '/sites/NewProvision/doc1/' + FileLeafRef;
        var oUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativePath(decodedurl='" + sourceFile + "')/moveto(newurl='" + targetFile + "',flags=1)";
        $.ajax({
            url: oUrl,
            type: "POST",
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log(data);
            }
        });
    }
</script>

<div id="Grid">

The MoveFile function takes a parameter named "FileLeafRef" to specify the file name, and sourceFile/targetFile parameters are defined to dynamically set the file URL.

https://i.sstatic.net/EAvdF.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...

What are some helpful tools for organizing data from an External API in NodeJS and Express?

One of the tasks I'm currently working on involves connecting to an external API through my backend system. Data flow : External API -> My backend -> Client side Typically, I would use modules such as request or http to facilitate this p ...

Ways to invoke a function from a different JS file within a Mountebank response block

I need help with decorating the response of a mountebank. I am struggling to call a function from another js file within the response code block. Can anyone provide some guidance? The javascript file in question is: utils.js function getRandomCharAndNum( ...

An error popped up as I attempted to load an existing design within the vue-email-editor

https://i.stack.imgur.com/0ObU5.png Check out the code snippet below for the function I have created: editorLoaded() { this.$refs.emailEditor.editor.loadDesign(this.emailJson); console.log('editorLoaded'); }, ...

Unable to bring in a TypeScript library that was downloaded from a GitHub fork repository

Currently, I am working on developing a GitHub app using the probot library. However, I have encountered an obstacle as outlined in this particular issue. It seems that probot does not offer support for ESM modules, which are crucial for my app to function ...

choose and adjust elements within a three-dimensional scene using three.js

I have a JSON file containing object data that I load into my scene using ObjectLoader. After adding the objects to the scene, I want to customize their textures by adding parameters like THREE.SmoothShading and an envMap. I know how to find a specific obj ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Utilizing the power of JSF ajax with Bootstrap's data-toggle feature for radio buttons

Despite my efforts, I have not been able to find a definitive answer on SO. If this question has already been addressed, please point me in the right direction. This is what I currently have: (HTML) <span class="btn-group" data-toggle="buttons-radio" ...

The draggable functionality is malfunctioning once the image is enlarged with Jquery

When it comes to creating a viewport function using jquery.viewport, I'm faced with the challenge of integrating it with jQuery UI slider and a custom zoom function for images. I've also utilized a plugin to enhance the viewport functionality. T ...

Listen for an event on a button to show a specific div

Looking to have a div appear when the user clicks on a button. //html-code <div class="col-md-4"> <h4 class="service-heading">Social Media</h4> <p class="text-muted">This is the first line of text.</p& ...

What is the best way to utilize external module imports for SVG React components in a create-react-app project?

Understanding the Project Structure To ensure code reusability across multiple React projects, a specific project structure has been established: @foo/design: Includes design elements like raw SVG images @foo/ui: A React library based on Create React App ...

Troubleshooting: My jQuery script for fading in content upon document ready is not

I'm currently working on a website where I want everything to fade in when the user enters the site. Take a look at my code: var celyLogin = $(".container"); $(document).ready(function () { /*! Fades in page on load */ $("container") ...

Can values be extracted from a JSON object that is saved in a separate JavaScript file?

In my current project, I am creating unique tables dynamically and displaying them using JavaScript after making an AJAX call. Instead of writing individual code for each table, I'm looking to establish a standard layout where I can customize the desi ...

JavaScript code often contains dates that are formatted in various ways

I need to perform validation in JavaScript by comparing DATES and TIME. I need to have the date in dd/MM/yyyy format, but I am unsure of the format it is currently taking. After debugging the JavaScript code, I discovered the format. The screenshot below ...

Showcase your skills in CSS, HTML, and Javascript

I attempted to search for something similar but came up empty-handed. I have two buttons. When I click one of them, I want to hide a certain division, but it's not working as expected. The divs d2 and d3 are initially hidden when the page opens, whic ...

Function that recursively checks for the existence of an ID within a nested object structure

I need assistance in developing a function that can determine whether the link ID of an object or any of its children match a specific ID. For instance, if the link ID for Product paths is 51125095, the function should return true when this ID is passed in ...

Using Jquery to input selected dropdown values into a text input field

Currently, I am facing some challenges in achieving this task. My goal is to have the selected option from a dropdown list called programs_dropdown added to a text field named programs_input, with the option values separated by commas. For example: php, j ...

Unable to set an onclick function within a customized dojo widget

I have a custom widget that I've defined as shown below: dojo.declare('myWidget', [dijit._WidgetBase, dijit._Templated], { 'templateString':'<span>' + '<a dojoAttachPoint="linkNode" href="b ...

How to remove every instance of an item in an array based on its unique identifier using JavaScript

Is there a way to clean up an array of objects by removing duplicates with the same id? In this case, I only want to keep the object with id 1. This is my approach: let data = [{ "selected": true, "id": 3, "ProductName": "Aniseed Syrup", ...

Adjusting the height of an iframe in real-time

Looking for some help with adjusting the height of an iframe based on its src content. I have a basic understanding of JavaScript, but need some guidance on how to achieve this. Here is what I currently have: <iframe id="frame" scrolling="no" framebord ...