5

I have an HTML5 + jQuery application with a built in contact form that I wanted to hook into Sharepoint, and Lists seemed an ideal way to do that. I used the jQuery library SPServices to get this up and running, and I thought it was working great with the following javascript code:

// Use Sharepoint list for adding data.
function CreateNewItem(name, email, phone, seat_chosen) { 

// Time to try to submit the form to Sharepoint!

$().SPServices({ 
    operation: "UpdateListItems", 
    async: false, 
    batchCmd: "New", 
    listName: "Form Contacts", 
    valuepairs: [["Title", name], ["Email", email], ["Phone", phone], ["Seat_Clicked", seat_chosen]], 
    completefunc: function(xData, status) { 

        if (status == "success") {
            alert ("Thank you, " + $("#contact_name").val() + ", for your inquiry!" );
        }
        else {
            alert ("Unable to submit your request at this time.");
        }

    }
});
} 

But it turned out that this only works if you are authenticated/logged in, even though the List permissions is set to allow Anyonymous Add Items. If you aren't logged in you just get that soul-crushing 401 (Unauthorized) message from _vti_bin/Lists.asmx.

I found various references to this problem in Googling, but they were all numerous years old and started back with Sharepoint 2007 and SPServices .5 (now using .7.2), and most trails end alluding to some future version or update they hope will fix this and then...the trail goes cold.

Is there some way to accomplish adding items to a list anonymously without allowing the contents of the list to be viewed publicly? If I need to use something other than SPServices I can, but custom alteration of Sharepoint itself or it's server-side code is not doable in this case.

I'm really, really trying to stick with javascript to get this accomplished for a multitude of reasons.

2
  • 1
    Hi Brian, long time ago now I know but did you get this working in the end? Thanks. Aug 18 '16 at 10:00
  • @j.strugnell Indeed, I forgot all about this post! To be honest I'm extremely hazy in my memory of how I got around it, but I went and dug up the code I used. While I can't remember exactly what exactly it was that solved it, I'll share the code and hopefully it will be helpful.
    – BrianH
    Aug 18 '16 at 19:07
1

Thanks Brian,

I managed to get the following code working as a minimal proof of concept. It's basically a cut down version of yours.

function AddListItem() {
    var listTitle = "List Name";
    //Get the current client context
    context = SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(listTitle);
    //Create a new record
    var listItemCreationInformation = new SP.ListItemCreationInformation();
    var listItem = list.addItem(listItemCreationInformation);
    //Set the values
    listItem.set_item("Title", "Anonymous Title");
    listItem.update();
    context.load(listItem);
    context.executeQueryAsync(AddListItemSucceeded, AddListItemFailed);
}

function AddListItemSucceeded() {
alert('List Item Added.');
}

function AddListItemFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Even using that code I then had a problem that the required SharePoint JavaScript wasn't on the page. I think I used the answers on the following page to resolve that: TypeError: SP.ClientContext is undefined

In the end I went for a completely different solution. I can't believe how hard it is to create a simple anonymous form in SharePoint...

Thanks for your help.

1

It's actually been so long that I don't know that I can recall exactly what I did to solve this problem, but I have dug up the code I used that does work in my application. I believe the special sauce had something to do with an alternate way of accessing the library. The code is a bit long as it includes bug fixes for weird corporate load browsers not working in my application (especially Internet Explorer related), and lots of logging/error checking, but I hope it can help anyone else who deals with this issue in the future!

The javascript packages I'm using are SPServices 0.7.2, sp.core.js, sp.js, sp.runtime.js, and JQuery 1.8.3.

// Use Sharepoint list for adding data.
function CreateNewItem(name, email, phone, seat_chosen) { 

    function onQuerySucceeded() {

        alert ("Thank you, " + $("#contact_name").val() + ", for your inquiry!" );

        // Use the Cancel button to close the form politely, while clearing its contents.
        $("#cancel_form_button").click();

        $("#contact_form_submit_button").val("Contact Me");
    }

    function onQueryFailed(sender, args) {
        alert ("Unable to submit your request at this time.");

        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());

        // Use the Cancel button to close the form politely, while clearing its contents.
        $("#cancel_form_button").click();

        $("#contact_form_submit_button").val("Contact Me");

    }

    // Time to try to submit the form to Sharepoint!
    $("#contact_form_submit_button").val("Submitting...");

    // define a ClientContext for the specified SP site
    var ctx = new SP.ClientContext("/sharepointsite/");

    // attach a onRequestFailed function to the client context.
    ctx.add_requestFailed(function (sender, args) {
        alert ("Unable to submit your request at this time.");

        alert('Request failed: ' + args.get_message());

        // Use the Cancel button to close the form politely, while clearing its contents.
        $("#cancel_form_button").click();

        $("#contact_form_submit_button").val("Contact Me");
    });

    // GETS SITE FIELD INFO
    var web = ctx.get_web();

    ctx.load(web);
    /*ctx.executeQueryAsync(function () {
        alert("Title: " + web.get_title());
        alert("Description: " + web.get_description());
    });
    */

    // CREATE LIST ITEM   
    var list = ctx
        .get_web()
        .get_lists()
        .getByTitle('Sharepoint Contact List Name');

      // create a new item on the list
    var contact = list.addItem(new SP.ListItemCreationInformation());

    contact.set_item("Title", name); 
    contact.set_item("Email", email);
    contact.set_item("Phone", phone);

    // ensure that contact is saved during the query
    contact.update();

    ctx.executeQueryAsync(function () {
        //console.log("Id of new contact (success): ", contact.get_id());
        alert ("Thank you, " + $("#contact_name").val() + ", for your inquiry!" );

        // Use the Cancel button to close the form politely, while clearing its contents.
        $("#cancel_form_button").click();

        $("#contact_form_submit_button").val("Contact Me");

    }, function () {
        //console.log("Id of new contact (failed): ", contact.get_id());
        alert ("Unable to submit your request at this time.");

        // Use the Cancel button to close the form politely, while clearing its contents.
        $("#cancel_form_button").click();

        $("#contact_form_submit_button").val("Contact Me");

    });

    // A Watcher function using a timer to ensure this process is successful
    // Avoid console.log() calls to avoid company computer bug.

    window.contact = contact;

    var timerID = window.setTimeout(function ()
    {
        //alert ("trying timer...");
        if (window.contact.get_id() > 0)
        {
            // Submissions successful!
            // Trigger a message only if one wasn't already sent - using trick of text on submit button to test.
            if ($("#contact_form_submit_button").val() == "Contact Me")
            {
                //alert ("no need for this...");
                // Submission already completed, we're done here.
                return;
            }
            else
            {
                //alert ("Success?");
                // Generate success.
                //console.log("Id of new contact (success): ", contact.get_id());
                alert ("Thank you, " + $("#contact_name").val() + ", for your inquiry!" );

                // Use the Cancel button to close the form politely, while clearing its contents.
                $("#cancel_form_button").click();

                $("#contact_form_submit_button").val("Contact Me");
            }
        }

    }, 3000);

} 

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.