Showing posts with label custom List. Show all posts
Showing posts with label custom List. Show all posts

Thursday, January 25, 2018

Inserting data in custom list using javascript in SharePoint 2013




1. Create a SharePoint custom list : For an example such as below one




2. Create a javascript file and copy below code into that file.

function SaveVehicle() {

    var listName = "vehicleList";
    var newVINNumber = document.getElementById('txtVINNumber').value;
    var newVehicleYear = document.getElementById('txtVehicleYear').value;
    var newPlateID = document.getElementById('txtPlateID').value;
    var newCurrentMileage = document.getElementById('txtCurrentMileage').value;
   

    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, newVINNumber, newVehicleYear,
        newPlateID,newCurrentMileage, function () {
        console.log("New Item has been created successfully.");
    }, function () {
        console.log("Ooops, an error occured. Please try again.");
    });
}

function CreateListItemWithDetails(listName, webUrl, newVINNumber, newVehicleYear,
        newPlateID,newCurrentMileage, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "VINNumber": newVINNumber,
        "VehicleYear": newVehicleYear,
        "PlateID": newPlateID,
        "CurrentMileage" : newCurrentMileage
    };

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_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) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

3. Add a "Script Editor" or "Content Editor" Web Part and Add this line of code on clicking of submit button
Include the javascript file which is in step 2 with script tag.

<button onclick="SaveVehicle()">Submit</button>


You can use "Developer Tools" of Browser or "Start Debugging" from Visual Studio to