3

I created a blank form on a HTML webpage through my Sharepoint site called http://.../testform.html.

<form>
    <input type='text' id='name'>
    <input type='submit' id='submitdata' value='submit'><br>
</form>

and I'm trying to have the input submitted to a SharePoint list called Test.

So I came up with the below code and I tested it using the Script Editor Web Part and it worked.

  <script type="text/javascript">
  $(document).ready(function() {

      $('#submitdata').click(function() {
          var name = $('#name').val();
          var list = "Test";
          addListItem(name, list);
      });
  });

  function addListItem(name, listname) {

      var listType = "Custom List";
      var item = {'__metadata': {'type': 'SP.Data.TestListItem'},
          'Title': name
      }
      var siteUrl = "https://intelshare.intelink.gov/sites/carm"

      $.ajax({
          url: siteUrl + "/_api/web/lists/getByTitle('" + listname + "')/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("done");
          },
          error: function(err) {
              console.log(JSON.stringify(err));
          }
      });
  }
  </script>

However when I use the same code from the Script Editor webpart in the html page I get the error below:

The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again

i loaded

<script type="text/javascript" src="./jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="./jquery.SPServices.min.js"></script>

I tried looking the error up and I came up with calling data.d.GetContextWebInformation.FormDigestValue but do not know how to incorporate it as it errors out. I am new to java and need a budge on the right direction.

0

5 Answers 5

2

Found the answer on this page. Thanks for your input.

It appears that the error occurs because the form digest has been expired on the page.

so i used these functions

var webUrl = "https://weburl"

function getFormDigest(webUrl) {
    return $.ajax({
        url: webUrl + "/_api/contextinfo",
        method: "POST",
        headers: { "Accept": "application/json; odata=verbose" }
    });
}

function createListItem(webUrl, listName, itemProperties) {
    return getFormDigest(webUrl).then(function (data) {

        return $.ajax({
            url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
            type: "POST",
            processData: false,
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(itemProperties),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
            }
        });
    });
}    

and called them like this:

//Create a Task item
var taskProperties = {
    '__metadata': { 'type': 'SP.Data.TestListItem' },
    'Title': name,
};

createListItem(_spPageContextInfo.webAbsoluteUrl, 'Test', taskProperties)

.done(function (data) {
    console.log('Task has been created successfully');
})
.fail(function (error) {
    console.log(JSON.stringify(error));
});
0

try this ......

<div class="col-md-6">
                <div class="form-group">
                    <label class="col-md-4">Name:</label>
                    <div class="col-md-8">
                        <input name="CTName" id="CTName" type="text" class="form-control " />&#160;
                    </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-md-4">Phone: </label>
                    <div class="col-md-8">
                        <input id="CTPhone" type="text" class="form-control " />&#160;
                    </div>
                </div>

    <div class="row text-center mrgtop50">
        <a href="javascript: void(0);" id="Submit" class="btn btn-danger" onclick="ItemSubmit()">Submit</a>
    </div>

function ItemSubmit() {
            $("#Submit").click(function () {
            debugger;
                AddItemToList(listItemEntity);                
            });
        }
        function InitialData() {
        debugger;
            context = new SP.ClientContext.get_current();
            web = context.get_web();
            context.load(web);
            context.executeQueryAsync(onRequestSuccess, onRequestFailure);
        }
        function onRequestSuccess() {
            Url = web.get_url();
            debugger;
            GetListItemEntity(Url);
        }
        function onRequestFailure(sender, args) {
            alert("Error Occured:" + args.get_message());
        }
        function GetListItemEntity(webUrl) {
            var queryUrl = webUrl + "/_api/lists/getbytitle('--ListName--')?$select=ListItemEntityTypeFullName";
            $.ajax({
                url: queryUrl,
                method: "GET",
                headers: { "Accept": "application/json;odata=verbose" },
                success: onEntitySuccess,
                error: onEntityFailure
            });
        }
        function onEntitySuccess(data) {
            listItemEntity = data.d.ListItemEntityTypeFullName;
        }
        function onEntityFailure(err) {
            alert(err.statusText);
        }
        function AddItemToList(listItemEntity) {
            //reading text box values
            debugger;
                var CTName = $("#CTName").val();
                var CTPhone = $("CTPhone").val();

            try {
                var queryUrl = Url + "/_api/lists/GetByTitle('--ListName--')/items";
                $.ajax({
                    url: queryUrl,
                    type: "POST",
                    contentType: "application/json;odata=verbose",
                    data: JSON.stringify(
                        {
                            '__metadata': {
                                'type': listItemEntity
                            },
                            'Name' : CTName,
                            'Phone': CTPhone,

                        }),
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val()
                    }, success: onQuerySuccess,
                    error: onQueryFailure
                });
            }
            catch (ex) {
                alert("Exception" + ex.message);
            }
        }
        function onQuerySuccess(data, request) {

            alert("Contract Form Submitted");
            window.location = _spPageContextInfo.webAbsoluteUrl + "/SitePages/.....";
            return false;

        }
        function onQueryFailure(error) {

        }
7
  • This did not work. I clicked the link and nothing happened and the input boxes did not refresh. My code works on a webpart but not on a blank html page.
    – ShanayL
    Commented Sep 27, 2017 at 19:06
  • try the below with above code it will work
    – karthik
    Commented Sep 27, 2017 at 19:48
  • can you put it all together so I can see how it is supposed to look? I am confused.
    – ShanayL
    Commented Sep 27, 2017 at 19:50
  • 'ItemSubmit' is undefined
    – ShanayL
    Commented Sep 27, 2017 at 20:10
  • maybe you have forgotten this links <script src="bootstrap.min.js"></script> <script src="createdjsfile"></script>
    – karthik
    Commented Sep 28, 2017 at 11:37
0
Add this on top function ItemSubmit(), create separate js and the code from var context to end not HTML div



   var context;                                                                                                              
    var web;                                                                                                                      
    var listItemEntity;                                                                                                           
    var ItemID;                                                                                                     
    $(document).ready(function() {                                                
                 getSPOffset();                                                                                    
    SP.SOD.excuteFunc('sp.js','sp.ClientContext',InitialDate);                                        
    ItemSubmit();                                                                                                
            }

and create separate ascx file for HTML code and addthe js file link.

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />          
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600" rel="stylesheet" />
link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="bootstrap.min.js"></script>
<script src="createdjsfile"></script>
0

this is ascx file

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />          
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600" rel="stylesheet" />
link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="bootstrap.min.js"></script>
<script src="createdjsfile"></script>
<div class="col-md-6">
                <div class="form-group">
                    <label class="col-md-4">Name:</label>
                    <div class="col-md-8">
                        <input name="CTName" id="CTName" type="text" class="form-control " />&#160;
                    </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label class="col-md-4">Phone: </label>
                    <div class="col-md-8">
                        <input id="CTPhone" type="text" class="form-control " />&#160;
                    </div>
                </div>

    <div class="row text-center mrgtop50">
        <a href="javascript: void(0);" id="Submit" class="btn btn-danger" onclick="ItemSubmit()">Submit</a>
    </div>
0

this is JS file

var context;                                                                                                              
    var web;                                                                                                                      
    var listItemEntity;                                                                                                           
    var ItemID;                                                                                                     
    $(document).ready(function() {                                                
                 getSPOffset();                                                                                    
    SP.SOD.excuteFunc('sp.js','sp.ClientContext',InitialDate);                                        
    ItemSubmit();                                                                                                
            }
function ItemSubmit() {
            $("#Submit").click(function () {
            debugger;
                AddItemToList(listItemEntity);                
            });
        }
        function InitialData() {
        debugger;
            context = new SP.ClientContext.get_current();
            web = context.get_web();
            context.load(web);
            context.executeQueryAsync(onRequestSuccess, onRequestFailure);
        }
        function onRequestSuccess() {
            Url = web.get_url();
            debugger;
            GetListItemEntity(Url);
        }
        function onRequestFailure(sender, args) {
            alert("Error Occured:" + args.get_message());
        }
        function GetListItemEntity(webUrl) {
            var queryUrl = webUrl + "/_api/lists/getbytitle('--ListName--')?$select=ListItemEntityTypeFullName";
            $.ajax({
                url: queryUrl,
                method: "GET",
                headers: { "Accept": "application/json;odata=verbose" },
                success: onEntitySuccess,
                error: onEntityFailure
            });
        }
        function onEntitySuccess(data) {
            listItemEntity = data.d.ListItemEntityTypeFullName;
        }
        function onEntityFailure(err) {
            alert(err.statusText);
        }
        function AddItemToList(listItemEntity) {
            //reading text box values
            debugger;
                var CTName = $("#CTName").val();
                var CTPhone = $("CTPhone").val();

            try {
                var queryUrl = Url + "/_api/lists/GetByTitle('--ListName--')/items";
                $.ajax({
                    url: queryUrl,
                    type: "POST",
                    contentType: "application/json;odata=verbose",
                    data: JSON.stringify(
                        {
                            '__metadata': {
                                'type': listItemEntity
                            },
                            'Name' : CTName,
                            'Phone': CTPhone,

                        }),
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val()
                    }, success: onQuerySuccess,
                    error: onQueryFailure
                });
            }
            catch (ex) {
                alert("Exception" + ex.message);
            }
        }
        function onQuerySuccess(data, request) {

            alert("Contract Form Submitted");
            window.location = _spPageContextInfo.webAbsoluteUrl + "/SitePages/.....";
            return false;

        }
        function onQueryFailure(error) {

        }
1
  • How to perform the client validations, like txtbox, date validation, start date , end date, people picker value validation etc in the above form? also, i wanna redirect to the editform.aspx with the newly created ID as a query string param
    – dasarp
    Commented Oct 25, 2018 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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