Wednesday, October 6, 2010

Add list Items using JQuery


Recently i got an requirement where i was suppose to add list items using JavaScript as we did not have access to the server side code, and we were not able to write code on the server.
So Here we go...

  1. Add JQuery to your Layouts Folder and give reference to the CEWP

    <script type="text/javascript" src="/_layouts/jquery/jquery-1.3.2.min.js"></script>

  2. Add the Script which will initialize the Web Service and Create the XML

    $(document).ready(function() {

    $("#newTaskButton").click(function() {

    CreateNewItem($("#newTaskTitle").val());

    });

    });


    function CreateNewItem(title) {

    // The CAML to create a new item and set the Title field.

    var batch ="<Batch OnError=\"Continue\"> \

    <Method ID=\"1\" Cmd=\"New\"> \

    <Field Name=\"Title\">" + title + "</Field> \

    </Method> \

    </Batch>";

    // The SOAP Envelope

    var soapEnv =

    "<?xml version=\"1.0\" encoding=\"utf-8\"?> \

    <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \

    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \

    xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \

    <soap:Body> \

    <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \

    <listName>Tasks</listName> \

    <updates> \

    " + batch + "</updates> \

    </UpdateListItems> \

    </soap:Body> \

    </soap:Envelope>";


    // Build the URL of the Lists.asmx web service.

    // This is done by stripping the last two parts (/doclib/page) of the URL.

    var hrefParts = window.location.href.split('/');

    var wsURL = "";

    for (i = 0; i < (hrefParts.length - 2); i++) {

    if (i > 0)

    wsURL += "/";

    wsURL += hrefParts[i];

    }

    wsURL += "/Pilot/_vti_bin/lists.asmx";

    // Make the call by posting the SOAP Envelope.

    $.ajax({

    url: wsURL,

    beforeSend: function(xhr) {

    xhr.setRequestHeader("SOAPAction",

    "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");

    },

    type: "POST",

    dataType: "xml",

    data: soapEnv,

    complete: processResult,

    contentType: "text/xml; charset=utf-8"

    });

    }

    function processResult(xData, status) {

    // Process the result.

    $("#responseStatus").text(status);

    $("#responseXML").text(xData.responseXML.xml);

    }


  3. Create an HTML Control


    <input id="newTaskTitle" type="text" />

    <input id="newTaskButton" type="button" value="Create Task" />

    <h5>

    Response:

    <label id="responseStatus" visibility="false">N/A </label>

    </h5>

  4. Now All put together and you are done.....!!!!

No comments: