Do I require permissions to run SPServices on Sharepoint? - sharepoint

I require assistance with Sharepoint. I've tried multiple ways to retrieve data from a list and have had little to no success, after much reading and searching I'm still no further ahead.
I am using a list made by another user, which I can add,edit and delete items from. When calling this list using SPServices I seem to hitting a wall. Here is my third attempt at trying to access the list and now I have received a 404 response and responsetext is null.
The URL is correct, cause it actually loads the list of values.
If i have an empty webURL parameter, the parameter of responsetext has a helpful SOAP response stating the following:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.</faultstring><detail><errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">
List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
</errorstring><errorcode xmlns="http://schemas.microsoft.com/sharepoint/soap/">0x82000006</errorcode></detail></soap:Fault></soap:Body></soap:Envelope>
Here is my call which when I define the webURL to point to the list, it always returns a http 404 with responseText=null no matter what the url is. This is not very helpful. The Url I am pointing to loads the list.
function getListItems_RFC(){
var url = $().SPServices.SPGetCurrentSite() +
"/_vti_bin/listdata.svc/RFCExtract";
console.log("getListItems_RFC() "+ url);
$().SPServices({
operation: "GetListItems",
webURL: url,
async: false,
listName: "RFC Extract",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
completefunc:
function (xData, Status) {
console.log(Status); //outputs error
console.log(xData); //outputs array responseText:null and status:404
$(xData.responseXML).SPFilterNode("m:properties").each(function() {
var liHtml = "<li>" + $(this).attr("d:Title") + "</li>";
$("#debug").append(liHtml);
});
}
});
};
I have modified the url each possible way:
var url = $().SPServices.SPGetCurrentSite() +
"/_vti_bin/listdata.svc/"; //responseText=null, status:404
var url = $().SPServices.SPGetCurrentSite();//responseText=null, status:404
var url = "" //responseText=soapresponse above, status:500
Why is this not working??? What am I doing wrong???

Can you change your implemetation to something other ?
Your way is very complicated by my opinion. Third party libraries here are unnecessary.
Good way is to use out-of-box REST API or JSOM. It is easy to use.
I see you want to get list item Title field.
Use REST API this way:
http://site url/_api/web/lists/GetByTitle('Test')/items?$select=Title
Here you can find example:
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-lists-and-list-items-with-rest
https://www.c-sharpcorner.com/blogs/retrieve-sharepoint-list-items-using-rest-api
May be you can use for SharePoint 2010:
var myRestApiUrl = _spPageContextInfo.webServerRelativeUrl + "/_vti_bin/ListData.svc/RFCExtract?$select=Title";
var get = function (url) {
return jQuery.ajax({
url: url,
type: "GET",
processData: false,
headers: {
Accept: "application/json;odata=verbose",
}
});
};
get(myRestApiUrl)
.then(function(response){
// TODO: do actions with response
});

Related

Can JQGrid work with SharePoint result source REST API

I tried to see if I can use JQGrid to display SharePoint search results by querying SharePoint result source with REST API.
The code to use REST API to call result source works in browser and Postman:
var apiUrl =_spPageContextInfo.webAbsoluteUrl +/_api/search/query?querytext='Mike'&rowlimit=100&selectproperties='RequestNameOWSTEXT, SubmittedByOWSUSER,ExaminiationNameOWSTEXT,PublishedDate1OWSDATE&sourceId='d90c19xx-7b3x-42bx-8fbx-d1dxxxx543ffa7', many results are returned.
But when I used it in JQGrid, got an error at line 44: Uncaught TypeError: Cannot read property 'length' of undefined
$.ajax({ url: apiUrl,type: "GET", async: false, headers: { "accept": "application/json;odata=verbose" }, success: function (data) {
line 44: $.each(data.d.results, function (index, value) { .............................
I guess the api call doesn't return result so the data is undefined. Wondering is something wrong with that api?
A different api like below works to return results:
var apiUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('documentrequest')/Folders?$expand=ListItemAllFields,AuthorID/id&$select=Name,ItemCount,ListItemAllFields/AuthorId,ListItemAllFields/ExaminiationName,ListItemAllFields/PublishedDate1&$filter=Name ne 'Forms' and ItemCount gt 0";
How to debug
You should check if the rest api returns values correctly.
Check whether the type of the variable using length has a length attribute.
It works, I figured out.. SharePoint search api itself provides only Filename, ContentTypeID, and Path. I use those values to run another api call to get the meta data, then add the values to array, which is used to feed the jqgrid.
Just get all the data into array, then feed to jqgrid when the data is ready.

How to create site content type with id using REST API

I want to create new Content Type which will be child of existing Content Type - Workflow Task (SharePoint 2013) using REST API.
So when I create request, I include parent Content Type Id in new Id.
I have tried following code.
const api = '/_api/web/contenttypes';
const requestBody = {
'__metadata': {
'type': 'SP.ContentType',
},
'Description': 'This is content type',
'Name': 'TestContentType',
'Group': 'TestContentTypeGroup',
'Id': {
   '__metadata': {
'type': 'SP.ContentTypeId'
},
'StringValue': '0x0108003365C4474CAE8C42BCE396314E88E51F000x010056401AE39A088645AD0597364A428033'         
}
};
const requestHeaders = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': <digestValue>
};
const requestData = JSON.stringify(requestBody);
var executor = new SP.RequestExecutor(<AppWebUrl>);
executor..executeAsync({
url: '<BaseUrl>' + api,
method: 'POST',
body: requestData,
headers: requestHeaders,
success: res => {
console.log(res);
},
error: error => {
console.log(error);
}
});
It does create new content type TestContentType but it inherits from Item Content Type and it does't have same Id which I provided in request. It randomly generates any id.
Can anyone please help with that?
This is actually a bug in the REST API...
Here is a link to an issue ,filed for the PnP JS library, where adding a content type is implemented the same way as you did: https://github.com/pnp/pnpjs/issues/457
Patrick Rodgers also filed an issue with Microsoft to resolve it: https://github.com/SharePoint/sp-dev-docs/issues/3276
This means that for now, unfortunately, there is no way of doing this with REST.
What you can do is upvote the issue to give it more visibility and hope it will be resolved soon.
As far I know this bug still persist. I found workaround which can help somebody who cannot use CSOM or JSOM. You can use Site script to define new site content type and specify parent content type name or Id. This site script you can wrap in a Site design and apply this Site design through REST API.
Unfortunately this workaround is useful only if you create the same site content type on different sites. And of course you can create multiple Site scripts and Site designs for each content type.

Passing JavaScript variable into snippet

I'm working on a search form for my ModX application that is consisted of a chunk and a snippet. What I'm trying to achieve is to pass what was entered into the search box into a javascript variable and then pass it to my snippet, however, the snippet receives the literal text, and not the value that I enter into the parameter when I call it.
I don't know if what I'm attempting is possible in ModX or if I need to take a different approach, but I would be hugely thankful for anyone who can provide any insight.
Chunk:
<script>
$('.search-btn').click(function() {
var search = $('.search-entry').val();
[[showSearchResults? &q=`search`]]
});
</script>
Snippet:
<?php
$search = $modx->getOption('q', $scriptProperties);
echo $search; // this always prints "search"
?>
I doubt that this code makes sense:
<script>
$('.search-btn').click(function() {
var search = $('.search-entry').val();
[[showSearchResults? &q=`search`]]
});
</script>
The snippet call returns the result of snippet's execution with param q always equal to the string 'search' in your case and finally on your page you will have something like this:
<script>
$('.search-btn').click(function() {
var search = $('.search-entry').val();
'search' // assuming your snippet just returns what has been passed to it.
});
</script>
In order to accomplish your task you can use a simple trick. Call your snippet like this:
[[!yourSnippet? &yourVar=`[[!#POST.yourVar]]` ]] // or GET
Lets say this snippet call is located on a page accessible via url /test/ on your server. So, now you just have to send the parameters you collected from your search form using AJAX to the /test/ page where your snippet is:
var yourVar = $('.search-entry').val();
$.ajax({
type: "POST",
url: "/test/",
data: {yourVar: yourVar},
success: success,
dataType: "html"
});
Hope it helps :)
PS If you want to search Resource content and TV content, I can highly recommend an extra called SimpleSearch.

Geocoding using Google Geocoding Web Service

I'm trying to geocode an address from Microsoft Dynamics CRM 2011 using Javascript.
I don't want to display the map, just perform the Geocoding and store the Lat / Long values in the database.
I keep getting an error message saying
"result.0 is null or not an object"
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=39 George Street, Belmont, WA, 6104, Australia&sensor=false'
var lat = url.results[0].geometry.location.lat();
alert(lat)
what am I doing wrong?
I assume from your question that this is a complete code snippet. On that assumption your code is incomplete. Your code creates a string called url. You then attempt to access a collection in that string, called results (which does not exist - and therefore position 0 within that colelction does not exist). Basically, your code doesn't do anything.
You need to have a good read of the Google Geocode API because, I'm sorry to say, you're not even close to getting this working... https://developers.google.com/maps/documentation/javascript/geocoding
Edit:
In the interests of being more helpful - here is a walkthrough too: http://www.wikihow.com/Geocode-an-Address-in-Google-Maps-Javascript
I have to disagree with Greg...you appear to have the request URL pretty close. Check out the Google Geocoding guide for the exacts. What you will get back is a JSON string, so you should use something like jQuery to parse the string into an object.
If you are not set on using JSON, then a simple script like this will also return the Lat/Lng (adapted from Google sample):
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var addressLocation = results[0].geometry.location;
alert("Lat: " + addressLocation.lat() + " Lon: " + addressLocation.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>

asp.net jqGrid dropdown multiselect

i'm trying to use jQuery multiselect plugin in a form editing jqGrid (add form).
This is the code (colModel extract) I'm using to build the dropdown:
{
name: 'CaratteristicheCamera',
index: 'CaratteristicheCamera',
width: 50,
hidden: true,
edittype: 'select',
editable: true,
editrules: { edithidden: true, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomFeatureList") %>',
buildSelect: function (data) {
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
var s = '<select id="CaratteristicheCamera" name="CaratteristicheCamera">';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
s += '<option value="' + response[i]["Id"] + '">' +
response[i]["Descrizione"] + '</option>';
}
}
return s + "</select>";
},
dataInit: function() {
$("#CaratteristicheCamera").multiselect();
}
}
},
As you guys can see, jqGrid call webmethod placed in asmx file. Everything seems to work ok, but I can't receive all the values user select from the dropdown. It seems that the system send to the server the last selection.
Do u have any tips on it?
EDIT: this is the asmx webservice declaration
[WebMethod]
public string SaveRoom(string id, string codice, string Numero, string NumeroPiano,
string Nome, string TipoCamera, string StatoCamera,
string CaratteristicheCamera, string TipoSdoppiabilita)
{}
I tried Eric Hynds jQuery UI MultiSelect Widget together with jqGrid 3.4.1 and couldn't see any problem which you described. I recommend you compare your demo with my to find the differences.
One bad thing which I see in your code is that you set id="CaratteristicheCamera" attribute on the <select> which you generate in buildSelect. You should just use <select> without any additional attributes. The jqGrid will set itself all attributes like id or multiple="multiple".
In the demo I used editurl: 'test.asmx/dummy' which not exist on the server. So one sees the error message like
after choosing and submitting the selected items
Nevertheless one can see with respect of tools like Fiddler, Firebug or Developer Tools of IE or Chrome (see HTTP traffic in "Network" tab) that the demo post the data like
{"name":"test8","closed":"No","ship_via":"FE,TN","oper":"edit","id":"8"}
to the http://www.ok-soft-gmbh.com/jqGrid/test.asmx/dummy. So the values "FE,TN" of selected items FedEx, TNT will be send as expected. In your case the CaratteristicheCamera parameter of SaveRoom should be initialized to the comma separated list of selected values. I hope you will find the problem in your code if you compare my demo with youth.
Another small problem in the code which you posted is that you make serialization to JSON manually in the WebMethod GetRoomFeatureList and returns string. So the string will be serialized to JSON twice. So you use
var retValue = $.parseJSON(data);
var response = $.parseJSON(retValue.d);
Correct will be to return something like List<Room>. ASP.NET will serialize it automatically. If you would use the jqGrid option
ajaxSelectOptions: {
contentType: 'application/json; charset=utf-8',
dataType: "json"
}
the data in buildSelect will be not needed to parsed at all. You can directly use data.d[i].Id and data.d[i].Descrizione in the loop. I wrone you about the same problem in another answer on your old question.

Resources