retrive the checkin comment using REST in sharepoint? - javascript

i have tried to update,checkout,checkin AND retrive the checkin comment but im getting value does not fall within the range error? anything i have missed ?
var getfileurl = document.getElementById("getfileurl").value;
//i have entered the path like /lib/folder/test.docx
alert(getfileurl);
var executor;
// Initialize the RequestExecutor with the app web URL.
executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: appweburl + "/_api/SP.AppContextSite(#target)/web/GetFileByServerRelativeUrl('" + getfileurl + "')/CheckInComment?#target='" + hostweburl + "'",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: SuccessHandler,
error: ErrorHandler
});

The error:
Value does not fall within the expected range
occurs since serverRelativeUrl parameter for SP.Web.getFileByServerRelativeUrl Method should be specified as server-relative URL for the file, for example:
/_api/web/GetFileByServerRelativeUrl('/site/web/library/filename')
Solution
Specify file url in the following format:
/site/hostweb/library/filename
for example:
var fileurl = _spPageContextInfo.siteServerRelativeUrl + "/documents/filename";

Related

Asp / ajax call web service and GET xml

My code returns : interne server error
var parameters = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3.org/2001/xmlschema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:body>" +
"<listeVille xmlns='http://..../b1'>" +
"<ville>"+ "Test" +"</ville>" +
"</listeVille>" +
"</soap:body>" +
"</soap:envelope>";
$.ajax({
type: "POST",
url: _URL_SITE + "webservices/b1.asmx",
dataType: "xml",
data: parameters,
contentType: "application/soap+xml; charset=utf-8",
headers: {
Accept: '*/*',
SOAPAction: 'http://.../webservices/b1/ListeVille' },
success: function (xml) {
alert('test');
//var _xmldoc
//_xmldoc = new activexobject("microsoft.xmldom");
//_xmldoc.async = "false";
//_xmldoc.loadxml(xml);
},
error: function () {
alert('error');
}
});
And my web service :
<WebMethod(True)> Public Function ListeVille(ByVal ville As String) As System.Xml.XmlDocument
Dim _xml As System.Xml.XmlDocument = New System.Xml.XmlDocument
Dim _hsh As New ParameterCollection
Try
_hsh.Add("#Ville", "")
_xml.LoadXml(_hsh)
Catch ex As Exception
AjoutJournal(ex)
End Try
Return _xml
End Function
I try to call my web service and get a xml file.
For information, don't focus on my function ListeVille, it returns the great value.
Thanks!
You are getting an Internal Server Error which means that there is an Exception in your server Side Code.
If you enable the Remote Errors then you can see the errors on the remote machine. Otherwise, if you debug the code on the machine, you can see the exception Details.
Moreover, the usage of XmlDocument.LoadXml Method doesn't seem to be correct as posted in your question. The Parameter to the LoadXml is a String containing the XML document to load. Try to pass in a valid XML. You can find more details on msdn here

jquery ajax inside loop return statusText error, Status 0 after certain time in IE

I m trying to update bulk of data one by one using Jquery ajax,so that i can show update progress. every thing goes well at beginning but after 5 min, it throw an error like in
Image while checking network request/respond:.
Error on error function of ajax:.
MainData is array of json object and is contain around 3000 number of json object.
function DoPost()
{
$.each(MainData, function (key, value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
success: function (res){
Progress(res); // this funtion will show progress of update.
},
error: function (res) {
console.log(res);
}
});
});
}
I am using web service of asp.net webform
The issue could be maximum number of concurrent connections to same URL. You can schedule next $.ajax() call when current $.ajax() completes.
See also multiple, sequential fetch() Promise
function DoPost(value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
return $.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'"
+ noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "POST",
success: function(res) {
Progress(res); // this funtion will show progress of update.
},
error: function(res) {
console.log(res);
}
});
}
var copy = MainData.slice(0);
var res = (function re(value) {
return DoPost(value).then(function() {
return copy.length ? re(copy.shift()) : "complete"
})
})(copy.shift());
res.then(function(complete) {
console.log(complete)
}, function(err, textStatus, jqxhr) {
console.log(err)
});
The error 0x2ee2 is IE's representation of timeout error. The occurrence of this error shows that the server has stopped responding to the requests due to a high number of requests sent from the same client. This is the server avoiding DOS attacks from the client.
The proper method is to optimize the code and try to utilize the maximum available bandwidth in order to minimize the number of requests to the server.

applyTheme via Javascript in SharePoint

I'm trying to apply a theme in another site collection via JSOM and REST.
I get a 404, that the file is not found. It doesn't matter if i choose another spcolor or spfont file. The result is still the same.
What am I doing wrong?
var applyTheme = {
url: urlToSiteCollection + "/_api/web/applytheme(
colorpaletteurl='/_catalogs/theme/15/palette007.spcolor',
fontschemeurl='_catalogs/theme/15/fontscheme007.spfont',
backgroundimageurl='/piclibrary/th.jpg',
sharegenerated=true)",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": digest
},
contentType: "application/json;odata=vebose",
success: function (applyThemeData) {
alert("Applyat theme");
},
error: function (ex) {
alert(JSON.stringify(ex));
}
};
$.ajax(applyTheme);
And the JSOM code:
var clientContext = new SP.ClientContext(urlToSiteCollection);
var web = clientContext.get_web();
var colorPaletteUrl = urlToSiteCollection + "/_catalogs/theme/15/palette011.spcolor";
var fontSchemeUrl = urlToSiteCollection + "/_catalogs/theme/15/fontscheme002.spfont";
var backgroundImageUrl = imageUrl;
var shareGenerated = true;
web.applyTheme(colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated);
web.update();
clientContext.executeQueryAsync(onApplyThemeSuccess, OnFailure);
Most likely you are getting this error since the endpoint:
http://<sitecollection>/<site>/_api/web/applyTheme(colorPaletteUrl,fontSchemeUrl,backgroundImageUrl,shareGenerated)
expects values for colorPaletteUrl,fontSchemeUrl,backgroundImageUrl parameters to be specified as server relative url, for example: /<site server relative url>/_catalogs/theme/15/palette007.spcolor
The following example works for me
var siteUrl = _spPageContextInfo.siteServerRelativeUrl;
var options = {
colorpaletteurl: _spPageContextInfo.siteServerRelativeUrl + '/_catalogs/theme/15/palette007.spcolor'
};
applyTheme(siteUrl,options)
.done(function (result) {
console.log("Theme has been applied");
})
.fail(function (ex) {
console.log(JSON.stringify(ex));
});
where
function applyTheme(siteUrl,parameters){
var requestUrl = siteUrl + "/_api/web/applytheme(";
var paramUrls = [];
for(var p in parameters) {
paramUrls.push(p + "='" + options.colorpaletteurl + "'");
}
requestUrl += paramUrls.join(',') + ")";
return $.ajax({url: requestUrl,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
contentType: "application/json;odata=vebose",
});
}
When you create a new context using SP.ClientContext(url) the url parameter needs to point to a site within the current site collection. The SharePoint JavaScript client object model does not support access across different site collections.
An alternative would be to use REST or SharePoint's other web services to access the other site.

What is the right way to use "context:..." in an AJAX call?

So I'm aware that there are a big amount of threads about AJAX and the use of the context but after hours of reading and trying I open a new Thread.
So I have this (shorten version) javascript function:
this.CallService = function () {
var Type = this.Type;
var Url = this.Url;
var Data = this.Data;
var ContentType = this.ContentType;
var DataType = this.DataType;
var ProcessData = this.ProcessData;
var ClipUrl = this.ClipUrl;
var CountMax = this.CountMax;
var Callback = this.Callback;
var SucceededServiceCallback = this.SucceededServiceCallback;
var FailedServiceCallback = this.FailedServiceCallback;
return $.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
context: this,
}).done(function (msg) {//On Successfull service call
SucceededServiceCallback(this, msg);
}).fail(function (msg) {
FailedServiceCallback(this, msg);
});
}
The Important part here are the context: this and the two callbacks done and fail. Im those two callbacks I give the this context to my callback functions:
this.SucceededServiceCallback = function (context, result) {
if (null != context) {
UpdateDebugInfo(context, "succeeded: " + context.DataType + " URL: " + context.Url + " Data: " + context.Data + " Result: " +result);
}
if (context != null && context.DataType == "json" && result != null && context.Callback != null) {
context.Callback(context, result);
}
}
Here the important part is that I use the context to see access the variables DataType, Callback, Url etc.
The Problem now is that the context is set to the last context used (it's an asynchron call so all the variable are the variable from the last call). So I'm pretty sure something is wrong with that context: this, part. I just don't know how to use this right. Thanks for your help.
tl;dr:
I use context: this in an Ajax call. Context is always set to the last "this" called. I want to use the "this" of the call.
You are "caching" all your variables before you fire each request, but in your SucceededServiceCallback function you are inspecting this.XXX - which is not the var Type it looks like you are expecting, but the actual this.Type itself.
What you could do is put these properties into an object and pass it as context, rather than your main object:
this.CallService = function () {
var context = {
Type : this.Type,
Url : this.Url,
Data : this.Data,
ContentType : this.ContentType,
DataType : this.DataType,
ProcessData : this.ProcessData,
ClipUrl : this.ClipUrl,
CountMax : this.CountMax,
Callback : this.Callback
};
var SucceededServiceCallback = this.SucceededServiceCallback;
var FailedServiceCallback = this.FailedServiceCallback;
return $.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
context: context,
}).done(function (msg) {//On Successfull service call
SucceededServiceCallback(this, msg);
}).fail(function (msg) {
FailedServiceCallback(this, msg);
});
}

Extracting data from JSON with ASP.Net web service

I am trying unsuccessfully to extract the formatted_address property.
The following web service logs the JSON below to the console. I cannot get the formatted address using returnedData.d.results[0].formatted_address.
$.ajax({
type: "POST",
url: "ReportIncident.aspx/ReverseGeocode",
data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (returnedData)
{
console.log(returnedData);
}
});
The format of the json is the exact same as the format over here at Google.
Edit
Darin pointed out that I was contradicting myself: the web service wraps up everything in the link above in a d object, I failed to mention that.
Further edit
Here is the web service:
[WebMethod]
public static string ReverseGeocode(decimal latitude, decimal longitude)
{
// Create the web request
string url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude +"&sensor=true";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
and here is the javascript:
/Gets the current location of the user
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type: "POST",
url: "ReportIncident.aspx/ReverseGeocode",
data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (returnedData)
{
alert(returnedData.d[0].results[0].formatted_address);
console.log(returnedData);
}
});
Have you tried using returnedData.results[0].formatted_address without the .d. node. That does not exist!
remove the ".d"
returnedData.results[0].formatted_address
but doing this you are always getting the first node only
The answer to this issue turns out to be that the web service is returning a string, instead of json. The built-in javascript serializer does not get used. The eval keyword or something more secure needs to be used. As it happens I ended up using the Google Maps Javascript API and that was much easier anyway.

Categories