0

I am loading all my data with a GET to populate to a DataTable. When a row is selected and drawn to a new table, it deletes from the DataTable as well as the SharePoint list it came from. I am trying to then populate a new SharePoint list with the deleted row, using the rowNode to populate an item data: JSON.stringify(item); to post to the list. I have all of the fields correct, but I am getting a 400 error when trying to execute it? I have tried debugging and cannot figure it out, it tells me in the network tab that it failed to load response data?

Here is my code: loading data to populate to the DataTable

function loadTasks() {
    var uri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('TestDynamicTaskList')/items?$expand=AssignedTo&$select=Title,Priority,ID,Status,StartDate,DueDate,PercentComplete,AssignedTo/Title,AssignedTo/Id";
    $.ajax({
        url: uri,
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: function(data) {
            if (data.d != null && data.d != undefined && data.d.results.length > 0) {
                console.log(data);
                var table = $('#taskTable').DataTable();
                table.rows.add(data.d.results).draw();
            }
        },
        error: function(error) {
            alert("Status: " + textStatus);
            alert("Error: " + errorThrown);
        }
    });
}
$('#taskTable tbody').on('click', 'tr', function() {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    });

    $('#button').click(function() {
        var selRowData = table.row('.selected').data();
        table.row('.selected').remove().draw(false);
        console.log(selRowData.AssignedTo.results[0].Id);
        console.log(selRowData.Priority);
        console.log(selRowData.Title);
        console.log(selRowData.Status);
        console.log(selRowData.StartDate);
        console.log(selRowData.DueDate);
        console.log(selRowData.PercentComplete);
        var listItemID = selRowData.ID;

        var item = {
            "__metadata": { "type": "SP.Data.TestDynamicTaskList2ListItem" },
            "AssignedToId": {
                "results": [
                    selRowData.AssignedTo.results[0].Id
                ]
            },
            "Priority" : selRowData.Priority,
            "Title" : selRowData.Title,
            "Status" : selRowData.Status,
            "Start Date": selRowData.StartDate,
            "Due Date": selRowData.DueDate,
            "Percent Complete" : selRowData.PercentComplete
        };

        completedTaskTable
            .row.add(selRowData)
            .draw();
            deleteCertTask(listItemID);
            insertCompletedTask(item);
    });

    function deleteCertTask(listItemID){
    var url2 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('TestDynamicTaskList')/items("+listItemID+")";
    $.ajax({
        url: url2,
        method: "DELETE",
        contentType: "application/json; odata=verbose",
        headers: {
            "Accept": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*",
            "X-HTTP-Mthod": "DELETE",
        },
        dataType: "json",
        success: function(data){
            alert("Item has been successfully deleted!");
        },
        error: function(error) {
            alert("Status: " + textStatus);
            alert("Error :" + errorThrown);
        }
    });
    }

    function insertCompletedTask(item){
        $.ajax({
          url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('TestDynamicTaskList2')/items",
          method: "POST",
          credentials: 'include',
          data: JSON.stringify(item),
          headers: {
              Accept: "application/json;odata=verbose",
              "Content-Type": "application/json;odata=verbose",
              "X-RequestDigest": $("#__REQUESTDIGEST").val(),
              "X-HTTP-Method": "POST",
          },
          success: function (data, status, xhr) {
              alert("New Form Item Created Successfully");
          },
          error: function (xhr, status, error) {
              alert(JSON.stringify(error));
              console.log(error);
          },
      });
    }

Everything works except for when insertCompletedTask(item); is executed. It even shows me what (item) is in the console and everything looks correct? In the local scope it shows the item and every column/piece of data associated with it is what it is supposed to be.

I get message: "textStatus is not defined" followed by Error 400

After it goes through the insertcompletedTask(item), it goes back up to deleteCertTask and error throws a readyState 4, error 200. But it still deletes the list item?

2

In a Tasks list, "Assigned To" is a multi user column. For user fields, SharePoint exposes a "shorthand" way to get and set the field using only the user ID by adding a suffix "Id" to the name of the field, so in this case it would be "AssignedToId".

You're not seeing that "shorthand" because you are $selecting AssignedTo/Title,AssignedTo/Id and then $expanding the Assigned To field, which causes the full expansion of the field and bypasses the "shorthand" version.

If the user column is a single user only, you can just assign the user ID directly to the shorthand version of the field name. But Assigned To is multi-user, so even if you are only setting a single user, you have to set it using a results array.

So try setting up your JSON like this:

var item = {
    // ... etc...
    "AssignedToId": {
        "results": [
            selRowData.AssignedTo.results[0].Id
        ]
    }
    // ... etc...
}
3
  • I updated my question reflecting your answer, I am still getting a 400 Error
    – BeerusDev
    Aug 26 at 12:30
  • fixed it, it was how I had the keys set up in the item object
    – BeerusDev
    Aug 26 at 13:23
  • Dylan, if you have a chance can you please take a look. I console.log( selRowData.Author.Id) and it is exactly what I expect it to be, but it will not allow me to post that value to a person or group column. sharepoint.stackexchange.com/questions/297516/…
    – BeerusDev
    Sep 14 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.