0

I have build a custom drop down field using HTML, the values in dropdown choice are coming from SharePoint list using GET API. I also added button with name "AddItem" in front of dropdown so when user click on that button it should send data into SharePoint list. My GET API is working fine but when it comes to POST API it is not sending the selected value in dropdown into SharePoint list.

Here is my full code:

<!DOCTYPE html>
<html>
<head>
<title>HTML form with dropdown select</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
<style>
    #country {
        height: 35px;
        border: 1px solid #ddd;
        padding-left: 10px;
    }
</style>
</head>
<body>
   <select id="projectDropdown" style="width: 200px;"></select>
<button id="addItemBtn">Add Item</button>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script>
 $(function(){
  $("#projectDropdown").select2();
 }); 
</script>

<script type="text/javascript">


    // Step 1: Clear existing options in the dropdown
    function clearDropdown(dropdown) {
        while (dropdown.firstChild) {
            dropdown.removeChild(dropdown.firstChild);
        }
    }

    // Step 2: Query the Project Online API to fetch all project data
    const apiUrl = 'https://teqmantrain.sharepoint.com/sites/PWADemo1/Demo01/_api/web/lists/getbytitle('Demo%20list')/items';
    fetch(apiUrl, {
        method: 'GET',
        headers: {
            'Accept': 'application/json;odata=verbose',
            // Include any required authentication headers here
        }
    })
    .then(response => response.json())
    .then(data => {
        // Step 3: Extract project names from the API response
        const items = data.d.results;
        const itemTitles = items.map(item => item.Title);

        // Step 4: Display or process item titles as needed
        populateDropdown(itemTitles);
    })
    .catch(error => {
        console.error('Error fetching item data:', error);
    });

    function populateDropdown(names) {
        // Example function to populate dropdown with project names
        const dropdown = document.getElementById('projectDropdown'); // Assuming there's a <select> element with id 'projectDropdown' on the PDP
        clearDropdown(dropdown);
        names.forEach(name => {
            const option = document.createElement('option');
            option.textContent = name;
            dropdown.appendChild(option);
        });
    }

// Function to add new item to SharePoint list
    $('#addItemBtn').click(function () {
        var selectedProject = $('#projectDropdown').val(); // Get the selected project from the dropdown
        var item = {
            '__metadata': { 'type': 'SP.Data.Demo%20listListItem' },
            'Assign': selectedProject, // Use the selected project as the Title
            // Add other fields as needed
        };

        $.ajax({
            url: "https://teqmantrain.sharepoint.com/sites/PWADemo1/Demo01/_api/web/lists/getbytitle('Demo%20list')/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) {
                // Item created successfully, refresh list
                alert("Item added successfully!");
            },
            error: function (error) {
                console.log(JSON.stringify(error));
                alert("Error adding item. Please try again.");
            }
        });
    });

</script>
</body>
</html>

Can anyone let me know why my POST API is not working?

4
  • Do you get any error? If yes, what is the error message? Or SharePoint site page refreshes automatically on click of button? Apr 9 at 14:15
  • yes, my sharepoint site page refresh when i click on AddItem button . And i did not get error in it but I did get alert which i added in my code alert("Error adding item. Please try again.") this is the alert that i am getting
    – Sourav
    Apr 9 at 15:33
  • Add type to your button element like: <button type="button" id="addItemBtn">Add Item</button>. Then check the error message logged in browser console (line before your alert function). Apr 9 at 16:26
  • Failed to load resource: the server responded with a status of 400 () Uncaught ReferenceError: g_PJPrefetch is not defined at m (shell.js:2:36531) at s (shell.js:2:36287) at e (shell.js:2:5124) at XMLHttpRequest.o (shell.js:2:5072) these 2 errors i am getting
    – Sourav
    Apr 9 at 16:44

0

Your Answer

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