Kavita2023
Kavita2023

Reputation: 11

ASP.NET Calling SharePoint Rest Api with jQuery AJAX getting "401 (Unauthorized)"

/ASP.NET Calling SharePoint Rest Api with jQuery AJAX getting "401 (Unauthorized)"/

Please help in authorization part

'Authorization': "NTLM " +btoa(username:password)
Add Item to SharePoint List


<h1>Add Item to SharePoint List</h1>

    Username:
    <br>
    Password:
    <br>
    Add Item


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        $('#addItemForm').submit(function(event) {
            event.preventDefault(); 

            const siteUrl = 'https://your-sharepoint-site-url.com'; // Update with your SharePoint site URL
            const listTitle = 'YourListTitle'; // Update with your SharePoint list title
            const endpointUrl = `${siteUrl}/_api/web/lists/getbytitle('${listTitle}')/items`;

            const newItemData = {
                'Title': 'New Item Title',
                'Description': 'This is a new item added from an external application.'
                // Add more properties as needed for your SharePoint list columns
            };

            const username = $('#username').val();
            const password = $('#password').val();
            const basicAuth = 'NTLM ' + btoa(username + ':' + password);

            $.ajax({
                url: endpointUrl,
                type: 'POST',
                headers: {
                    'Accept': 'application/json;odata=verbose',
                    'Content-Type': 'application/json;odata=verbose',
                    'Authorization': "NTLM " +btoa(username:password)
                },
                data: JSON.stringify(newItemData),
                success: function(data) {
                    console.log('New item created successfully:', data);
                    // Optionally, display a success message to the user
                },
                error: function(error) {
                    console.error('Error creating new item:', error);
                    // Optionally, display an error message to the user
                }
            });
        });
    });
</script>

Upvotes: 0

Views: 32

Answers (0)

Related Questions