1

I am currently playing with a company SharePoint online with a view to make it look more "websitey".

I am having trouble sending the form information to a SharePoint list (called "Tasks". I am trying to create a new item.

Here is the list on SharePoint default view: Sharepoint Task List

I am able to pull the list and put it on DataTable on the SharePoint site as shown below: DT sharpoint List

I am using a Modal to make the form functional.

  <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModalHorizontal">Add A Task</button>

× Close Add A Task

        <!-- Modal Body -->
        <div class="modal-body">

            <form class="form-horizontal" role="form" id="form_id" method="post">



              <div class="form-group">
                <label class="col-sm-2 control-label"
                      for="TasksForm" >Task</label>
                <div class="col-sm-10">
                    <textarea name="Task" id="TasksForm" style="height: 200px; width: 300px"></textarea>
                </div>
              </div>

              <div class="form-group">
                <label  class="col-sm-2 control-label"
                          for="EmployeeNameForm">Assign Task to:</label>
                <div class="col-sm-10">
                     <select name="Employees" class="form-control" id="employeeNameForm" style="width: 120px">
                          <option value="allstaff">All Staff</option>
                          <option value="a666">a</option>
                          <option value="b666">b</option>
                          <option value="c666">c</option>
                          <option value="d666">d</option>
                          <option value="e666">e</option>
                          <option value="f666">f</option>

                        </select> 
                </div>
              </div>

                            <div class="form-group">
         <label class="col-sm-2 control-label" 
                for="DueDateForm">Due Date</label>
         <div class="col-sm-10">
    <input class="form-control" id="date" name="date" placeholder="DD/MM/YYY" type="text" style="width: 120px"/>
                    </div>
        </div>
              <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-default" id="submit">Submit</button>
                </div>
              </div>
            </form>
        </div>

and the js I have for the submit button:

$("#submit").click(function addListItem(task, employeename, duedate, Tasks) {

var task = $('#TasksForm').val();
var employeename = $('#employeeNameForm').val();
var duedate = $('#date').val();
var listType = GetItemTypeForListName(Tasks);

function GetItemTypeForListName() {
    return "SP.Data." + Tasks[0].toUpperCase() + Tasks.substring(1) + "ListItem";
}
alert(listType);

// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
    "__metadata": { "type": listType },
    "Task": task,
    "Title": employeename,
    "DueDate": duedate
}
$.ajax({

    url: "https://website.sharepoint.com/sites/development/_api/web/lists/GetByTitle('Tasks')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (data) {
        console.log("Success!");
        console.log(data); // Returns the newly created list item information
    },
    error: function (data) {
        console.log("Error!");
        console.log(data);
    }
})

});

For the life of me, I really cannot figure out where I am going wrong. The page refreshes when I press "submit". no errors are shown. The in browser development console shows no errors loading the js on page.

  • What do you get in the Console.log? and can you try this instead: $("input[name='date']").val() – SharePointer May 24 '17 at 11:21
  • Your first screenshot is a "Modern Experiences" view. Microsoft has disabled all branding or custom JavaScript in Modern Experiences. Are you sure you are using Classic mode for your Form (not 100% sure, but I thought Modern and Classic couldn't mix) – Danny '365CSI' Engelman May 24 '17 at 11:30
  • @S Merchant: I cleared the cache (whoops) and now get "error!" Also Tried $("input[name='date']").val() and it doesnt make a difference. – SamKayPharma May 24 '17 at 13:47
  • @365CSI: Thank you for the comment. I have looked into what you said and it seems to only apply if I am directly editing the list aspx. I am just calling from the list and posting to the list through REST. as I am able to GET with REST, I suspect I would also be able to POST? I am not 100% sure that the modern experience would affect that - what do you think? – SamKayPharma May 24 '17 at 13:53
0

It's possible you are getting a posting error due to the Due Date field. SharePoint stores dates in the ISO format. Try something like this to convert your date before posting:

    if ($("#date").val()){
       inputDue = $("#date").val();
       dueDateTemp = new Date(inputDue);
       duedate = dueDateTemp.toISOString();
    }

In order to get more information in regards to the Ajax error, jQuery returns detail response information. You may access it in your error function like this:

    error: function(jqXHR, status, error){
        console.log(jqXHR);
        console.log("status="+ status);
        console.log("error=" + error)
    }
  • Thank you maleman for the tip - I added error: function(jqXHR, status, error){ console.log(jqXHR); console.log("status="+ status); console.log("error=" + error) } and it works well. The information it throws at me in console is very useful. – SamKayPharma May 25 '17 at 10:18
  • Alternatively, you can use console.error() for the error messages. It simply makes it red, like it would other errors shown in console. – wjervis May 25 '17 at 11:17
0

So I answered it and thought I'd post it for the record.

S Merchant pointed out a key fault - the date input. Thank you for that!

I changed the code as shown below:

$("#submit").click(function addListItem(task, employeename, duedate, listTitle) {

var listTitle = "Tasks"
var task = $('#TasksForm').val();
var employeename = $('#employeeNameForm').val();
var duedate = $("input[name='date']").val(); 
var listType = getItemTypeForListName(listTitle);


function getItemTypeForListName(listTitle) {
return"SP.Data." + listTitle.charAt(0).toUpperCase() + listTitle.slice(1) + "ListItem";
};

console.log(listType)

var item = {
    "__metadata": { "type": listType },
    "Task": task,
    "Title": employeename,
    "DueDate": duedate
}
$.ajax({

    url: "https://keypharmaceuticals.sharepoint.com/sites/development/_api/web/lists/GetByTitle('Tasks')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: 
    console.log("Success!"),
    error: 
    console.log("Error!")

    })
});

A few things seemed to be causing stresses in the code:

  • console.log(data) was not functioning. Got rid of it. God help us if we need to debug this in the future.

  • "var duedate = $('#date').val();" should have been: "var duedate = $("input[name='date']").val();"

  • function getItemTypeForListName(listTitle) required new code and a new variable.

  • I got rid of the alert for the listtype - that was mostly for my own reference.

  • Also very minor mistake - caching was enabled and the js files were cached so changes I made in SPD would not update! Look out for that one!

Thank you for all your help.

  • console.log() didn't work? Is this in IE? I know older versions of IE didn't create console until dev tools was open – wjervis May 24 '17 at 18:15
  • console.log() works fine (it can post things on the log) but the console.log(data) was throwing a bit of a tantrum so I threw it out... I did add maleman's error log feature and it works well so will be using that from now on. – SamKayPharma May 25 '17 at 10:17

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.