SharePoint: CRUD Operation using SPServices

Fill Drop Down List:

<script language="javascript" type="text/javascript">

/* ----------- Bind Dorp Down List - Country Begin -------------*/
var SPSiteURL = "https://yourSharepointsiteURL/Site";
 
        $().SPServices({
            webURL: SPSiteURL,
            operation: "GetListItems",
            async: false,
            listName: "Country",
            CAMLQuery: "<Query><OrderBy><FieldRef Name='Title'/></OrderBy><Where><Eq><FieldRef Name='Active'/><Value Type='Boolean'>1</Value></Eq></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>",
            completefunc: function(xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    var DataTextField = $(this).attr("ows_Title");
                    var DataValueField = $(this).attr("ows_ID");
                    listItem = "<option value=" + DataValueField + ">" + DataTextField + "</option>"
                    $("#ddlCountry").append(listItem);
                });
            }
        });
/* ----------- Bind Dorp Down List - Country End -------------*/
</script>

Above Code will get items from Country DropDownList where Active = True

Save:
Bind Save Button Event & Code to Save Data.

<script language="javascript" type="text/javascript">

//Submit Button Click Event
    $("#btnSubmit").click(function() {
        return SaveEmployeeInfo();
    });

/* ----------- Save Employee Info Form Code Begin -------------*/
function SaveEmployeeInfo()

{
    console.log("Save Process Begin");
    //alert("Save Event");

    var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    console.log("City = " + City);   

    console.log("Save Process Begin");

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get Item CreationInfo 
    var itemCreateInfo = new SP.ListItemCreationInformation();

    //Add Item Object
    this.oListItem = oList.addItem(itemCreateInfo);

    //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);
	

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onSaveQuerySucceeded), Function.createDelegate(this, this.onSaveQueryFailed));

    return false;
}

function onSaveQuerySucceeded() {

    console.log('Item created: ' + oListItem.get_id());
}

function onSaveQueryFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>

Update: Bind Update Button Event & Code to Update Data

<script language="javascript" type="text/javascript">


/* ----------- Update Employee Info By EmpID Code Start-------------*/
function UpdateEmployeeInfo() {
    
	//alert("Update Operation Begin");
	
    var EmpID = getParameterByName('EmpID');
	
	var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
	console.log("City = " + City);  
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get List Item By ID 	
    this.oListItem = oList.getItemById(EmpID);

   //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryAuditUpdateSucceeded), Function.createDelegate(this, this.onQueryAuditUpdatedFailed));

    return false;


}

function onQueryAuditUpdateSucceeded() {

    console.log('Item Updated Successfully');
}

function onQueryAuditUpdatedFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
/* ----------- Update Employee Info By EmpID Code End-------------*/

</script>


Retrieve Employee Data : Code to Retrieve Data

<script language="javascript" type="text/javascript">

/* ----------- Retrieve Employee Data Code Starts -------------*/
function GetemployeeData(EmpID) {
    $().SPServices({
        webURL: SPARPSiteURL,
        operation: "GetListItems",
        async: false,
        listName: "EmployeeInfo",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + EmpID + "</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='EmployeeName' /><FieldRef Name='City' /><FieldRef Name='Agreement' /><FieldRef Name='Hobbies' /><FieldRef Name='BirthDate' /></ViewFields>",

        completefunc: function(xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function() {

                console.log("ows_Title " + $(this).attr("ows_Title"));
                console.log("ID " + $(this).attr("ows_ID"));
                console.log("EmployeeName " + $(this).attr("ows_EmployeeName"));
                console.log("City " + $(this).attr("ows_City"));
                console.log("Agreement " + $(this).attr("ows_Agreement"));
                console.log("Hobbies " + $(this).attr("ows_Hobbies"));
                console.log("BirthDate " + $(this).attr("ows_BirthDate"));
              
                var City = $(this).attr("ows_City");
                $("#ddlCity").find("option:contains('" + City + "')").each(function() {
                    if ($(this).text() == City) {
                        $(this).attr("selected", "selected");
                    }
                });


                $("#txtEmployeeName").val($(this).attr("ows_EmployeeName"));

                var date = new Date($(this).attr("ows_BirthDate"));
                if (!date) {
                    var currentMonth = date.getMonth() + 1;
                    if (currentMonth < 10) {
                        currentMonth = '0' + currentMonth;
                    }
                    var currentDate = date.getDate();
                    if (currentDate < 10) {
                        currentDate = '0' + currentDate;
                    }
                    var PrePlanStartDate = (currentDate) + '/' + currentDate + '/' + date.getFullYear();
                    $("#txtBirthDatee").val(PrePlanStartDate);
                }

                if ($(this).attr("ows_Agreement") == 1) {
                    $('#chkAgreement').attr('checked', 'checked');
                };

                //---------Hobbies Check Box List
                console.log("Hobbies Value " + $(this).attr("ows_Hobbies"));
                var Hobbies = $(this).attr("ows_Hobbies");

                var arrayTeam = Hobbies.split(',');
                //console.log("Array Value" + arrayTeam);

                for (var i = 0; i < arrayTeam.length; i++) {
                    var chkValue = arrayTeam[i];
                    $("#chkHobbies input:checkbox").each(
                        function() {
                            if ($(this).attr("id") == chkValue) {
                                $(this).prop("checked", true);
                            }
                        }
                    );
                }

            });
        }
    });
}
/* ----------- Retrieve Employee Data Code Ends -------------*/
</script>
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s