javascript
17 TopicsCORS policy: Response to preflight request - JavaScript/SharePoint Server
I have an issue connecting to my SharePoint server. This issue occurs whenever I try connecting my code from the frontend to the SharePoint server, I do not have a backend for this. Basically, I am trying to get the SharePoint API results directly via JavaScript. I am uncertain why this error keeps popping up. Is there something wrong with my IIS configuration? Please do help me on this! Thank you! This is my IIS configuration in the SharePoint Server: <httpProtocol> <customHeaders> <add name="X-Content-Type-Options" value="nosniff" /> <add name="X-MS-InvokeApp" value="1; RequireReadOnly" /> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> Error Message: My code is as follows: function simpleSearchAPICall(searchUrl) { $.ajax({ url: searchUrl, type: "GET", contentType: "application/json; charset=utf-8", dataType: "json", complete: function(response){ console.log("URL", searchUrl) console.log(response); // Handle the response data here }, error: function(xhr, status, error) { console.error("ERROR:",error); // alert("An error occurred while making the request."); } }); simpleSearchAPICall("http://www.test.com/_api/search/query?querytext='test'") });699Views0likes0CommentsSharepoint CORS Policy issue persist even after ISS Configurations
I am currently trying to fetch my Sharepoint API via my code. However I am running into the issue below. I have already enabled the ISS Configurations as shown in the link below. However, the issue still persist. https://techcommunity.microsoft.com/t5/iis-support-blog/access-to-xmlhttprequest-from-origin-has-been-blocked-by-cors/ba-p/3800362 Error: index.html:1 Access to XMLHttpRequest at 'http://testing- sharepoint/Shared%20Documents/query%20result%20BEFORE.xml' from origin 'http://127.0.0.1:2233' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. My code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { function apiCallTest(searchValue) { const adminAccount = 'testUser'; const adminAccountPassword = 'testPassword'; const auth = btoa(`${adminAccount}:${adminAccountPassword}`); const testQuery = 'BEFORE'; const apiUrl= "http://testing-sharepoint/Shared%20Documents/query%20result%20BEFORE.xml" const headers = { 'Authorization': `Basic ${auth}`, // 'Accept': 'application/json;odata=nometadata', // 'Content-Type':'application/json', // 'Access-Control-Allow-Credentials':'TRUE', // 'Access-Control-Allow-Headers':'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization', // 'Access-Control-Allow-Origin':'*', // 'Access-Control-Allow-Methods':'GET,POST,PUT,OPTIONS' }; $.ajax({ url: apiUrl, headers: headers, method: 'GET', dataType: 'xml', success: function(data) { // Process the search results as needed console.log('Search Results:', data) }, error: function(xhr, textStatus, errorThrown) { console.log("Cannot connect") console.error('Error:', xhr, textStatus, errorThrown); } }); } function checkConnection(url) { if (navigator.onLine) { console.log(`You are online. Checking connection to ${url}...`); // You can attempt further actions here if needed } else { console.log('You are offline. Check your network connection.'); } } checkConnection("https://testing-sharepoint/_api/site"); apiCallTest(); }); </script> </head> <body style="background: black; color: aliceblue; font-size: 2rem;"> </body> </html>1.5KViews0likes0CommentsAdding custom javascript to sharepoint
Hi, i would like to create a webpart that pops up on a site at random location with something like "Congratz, you won!". I am absolutely new to sharepoint development, but i am very familiar with java. So i guess i can manipulate the DOM somehow with javascript and insert somewhere my visible part of the webpart. I followed https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part but i am already struggling. Where i can inject the javascript so it gets executed? Because everything is getting escaped (and the code is shown). I found some old code on one of our servers which "loads" some .js from inside a .ts like: link = document.createElement("script"); link.setAttribute('type', 'module'); link.setAttribute('src', srcPath); link.setAttribute(dataIdentifier, 'true'); and then adding it with document.head.appendChild(link), but i am not sure if this is really how this is supposed to work or if there is something like "addJavascript(...)" or any other better approach to add javascript on client side. Any help is very appreciated!16KViews0likes3CommentsSharepoint OAuth2.0 API Access
I created the API in share-point and saved all XML permission to the app, however I am getting the error code "-2147024891, System.UnauthorizedAccessException", I am able to get the access token. When passing the access token to the share-point API it is throwing the above mentioned error. Alternatively I tried to create the app in AzureAD and grant all the permission to the share-point App, and when getting the access token and while passing the access token to the share-point API it is throwing me the error code : "{"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}", Do anyone has the fix how resolve this error. I1.2KViews0likes1CommentGetting the MArquee JQuery library to work
Hi I have a very simple javascript, Housed in @MikaelSvenson 's excellent script editor for the Modern UI. I am trying to get an announcement from the Announcements list to display on a modern UI Page from Right to Left across the page. Just like the old fashioned Marquee HTML element. But nothing is being displayed. CAn anyone see why ? <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js"></script> <script type="text/javascript"> console.log("At start of REST Script"); $url = "https://<tenantname>.sharepoint.com"; $.ajax({ url: $url + "/_api/web/lists/getbytitle('Announcements')/items?select=*", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function(data) { console.log("Success"); console.log(data.d.results); var $dataArray = data.d.results; for (var $i in $dataArray) { console.log(data.d.results[$i].Title); var $str = $dataArray[$i].Body0; var $gtindex = $str.indexOf(">"); $gtindex = $gtindex + 1; $str1 = $str.substring($gtindex); console.log($str.substring($gtindex)); var $ltindex = $str1.indexOf("<"); console.log($ltindex); console.log($gtindex); var $length = $ltindex -$gtindex; var $innertext = $str1.substring(0,$ltindex); console.log($innertext); var $bodyHtml = "<li>" +$innertext + "</li>"; $("marquee").append($bodyHtml); } }, error: function(data) { console.log("Failure"); alert(JSON.stringify(error)); } }); $("#marquee").marquee(); console.log("At End of Script"); </script> <ul id="marquee" class="marquee" /> Apologies for some of the code I have been debugging it. Thanks Nigel1.2KViews0likes1CommentNext Js as WebPart
Hi there, I have an application that was made using Next Js and my team wants to put it on a share point page, I have been trying to find information to know if this is even possible. I found WebParts but I am not sure if that is compatible with Next Js and I haven't found any resources that could help me with this. Any help will be appreciated. Thanks.3.9KViews0likes1CommentLoad predefined data from columns and update field with possible selection with Javascript
I am struggling with piece of code. I am working on SharePoint 2013 and I am trying to set 2 fields fixed when creating a new item in list. All 3 fields are lookup columns, but the red highlighted fields I want to set as fixed and the yellow highlighted field is conditioned by the field Vyberova_Skupina_Sluzba Also Vyberova_Skupina_Sluzba is conditioned by the field Vyber_Oblast I used the part of the code below, the fields are fixed Vyber_Oblast and Vyberova_Skupina_Sluzba but third column is not updated. function nastavSluzba(){ $('#Produktova_Skupina_Sluzba').find('select').val('Hypotekárne úvery'); $('#Vyber_Oblasti').find('select').val('Úverové produkty pre FO') $('#tableNapoveda').remove(); $("#Vyber_Oblasti").find('select').attr("disabled", true); $("#Produktova_Skupina_Sluzba").find('select').attr("disabled", true); $("#Vyber_Oblasti").find('select').css({"background-color": "white","color": "black"}); $("#Produktova_Skupina_Sluzba").find('select').css({"background-color": "white","color": "black"}); var allOptions = document.querySelectorAll("[title=Vyber_Oblasti] option"); [].some.call(allOptions, function(option) { if (option.innerHTML == "Úverové produkty pre FO") { option.selected = "Úverové produkty pre FO"; return true; } }); var allOption = document.querySelectorAll("[title=Produktova_Skupina_Sluzba] option"); [].some.call(allOption, function(option) { if (option.innerHTML == "Hypotekárne úvery") { option.selected = "Hypotekárne úvery"; return true; } }); Can you help me make sure that the third field is loaded automatically and that the user can select an option that falls under Produktova_Skupina_Sluzba ?672Views0likes0CommentsCannot add new item to ECB Menu - SharePoint 2019
Hello, We just migrated from SharePoint 2013 to 2016, then 2019. We create items in the menu in JavaScript via the CAMOpt () function. In 2013 and 2016, everything is working perfectly, but not in 2019. The "m" parameter in the function CAMOpt is constantly null and the item is not added. CAMOpt(m,"Add to...","AddTo('"+listName + "'," + currentItemID +");"); The issue is identical to the following topic (which has been closed and reported as a bug): https://social.technet.microsoft.com/Forums/lync/en-US/8f464806-2c4d-4907-8c2c-fd7d86129d7c/cant -add-element-to-ecb-menu-in-sharepoint-2019? forum = SP2019 I cannot use JSOM to add to the menu permanently because I want the item only appear on a particular page and "SP Callout actions" is not working for custom list / generic list. Do you know a solution or a workaround ? Thanks in advance Nathan926Views0likes0CommentsUpdate Group SharePoint Custom Field Collums after Fileupload with REST Graph API in Javascript
Hi, I've made an upload with Graph with the following JS code: async function uploadSingleFileMetaToSharepoint(file, name, metaData, groupId, graphAccessToken) { //console.log(file, name, metaData, groupId); //TODO get Filepath from config of App let pathToFiles = 'General' let apiurl = msgraph + `/groups/${groupId}/drive/root:/${pathToFiles}/${name}:/content`; if (debug) { console.log("uploading File: ", file); console.log(`API-URL: ${apiurl}`); } let header = { 'Authorization': graphAccessToken, } let body = file; //TODO catch errors let result = await fetch(apiurl, { "method": 'PUT', "headers": header, "body": body }); if (!result.ok) { console.error("upload file to sharepoint failed"); return } let res = await result.json(); //console.log(res); if (res === undefined || res.id === undefined) {console.error("Die DAtei wurde nicht hochgeladen"); return;} /... } which is working fine. But now i'm struggling to fill the values of the collumns from sharepoint : Does anybody know how to approach this?Solved1.6KViews0likes1Comment