Call Sharepoint APIs from localhost - javascript

This thread is very similar to that question but I am not convinced by the answer given ("The library can't be used if the application is not deployed on the same sharepoint site domain") because in this page here the author insists on the fact that it is possible via the object SP.RequestExecutor(appweburl).
So I followed all the steps mentionned in the page and I ended up with this code:
$(document).ready(function () {
var hostweburl = decodeURIComponent("https://lpl.sharepoint.com/sites/TestPortail");
var appweburl = decodeURIComponent("http://localhost");
var scriptbase = hostweburl + "/_layouts/15/";
// Load the .js file using jQuery's getScript function.
$.getScript( hostweburl + "/_layouts/15/SP.RequestExecutor.js", continueExecution );
function continueExecution() {
var executor;
// Initialize your RequestExecutor object.
executor = new SP.RequestExecutor(appweburl);
console.log(executor); // just to see if created
// You can issue requests here using the executeAsync method
// of the RequestExecutor object.
executor.executeAsync({
url: appweburl + "/_api/SP.AppContextSite(#target)/web/title?#target='" + hostweburl + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
console.log('Successfully obtained data.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('There is an error.');
console.log(jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
}
});
}
});
When I executed it from localhost I get this:
I have been looking for the solution for 2 days. Maybe it is because the localhost is not a https, but even with this great answer I have not managed to do it (wamp won't start).
Any help would be appreciated.

Related

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.

JSON data in MS CRM 2011

I'm having an issue using JOSN data in MS CRM 2011. I am using the correct REST syntax to pull the CRM data but my JavaScript is the remaining issue.
What I want to do is append data from my JSON to a class of my choosing. I checked the console and no errors are apparent. Originially I believed once I had the JSON object I could pull the data from it using jQuery. Here is the code I currently have:
RetrieveScoutMetadata : (function(scout_displayable){
var query = "/scout_metadataSet?$select=scout_data_type,scout_display_name,scout_display_order,scout_displayable,ImportSequenceNumber,scout_name,scout_metadataId&$orderby=scout_display_order asc&$filter=scout_displayable eq "+scout_displayable+"";
ExecuteQuery(query);
})
RetrieveScoutOpportunity : (function(scout_account){
var query = "/scout_opportunitySet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
RetrieveScoutAccount : (function(scout_account){
var query = "/scout_accountSet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before
// using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteQuery(ODataQuery) {
var serverUrl = Xrm.Page.context.getServerUrl();
// Adjust URL for differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
alert("OData Execution Success Occurred");
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
$('.up-sell').append(account.scout_num_up_sells);
}
//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }
To get response use "complete" function:
complete: function (jsondata, stat) {
if (stat == "success") {
data = JSON.parse(jsondata.responseText);
}
}

Why will this code not create an Opportunity using Odata in Microsoft Dynamics CRM 2011?

Long story short, this code WILL create an Account when I change the URL ending to "AccountSet" but it WILL NOT do anything but give me a "Bad Request" error when I try creating a new Opportunity. Does anybody see something I am missing? Thank you so much for any help here. (Also, for the record, I did try CRMRestkit and got an error there too).
var newOpportunity = new Object();
newOpportunity.Name = "TEST";
newOpportunity.StatusCode = 0;
var contact = new Object();
contact.Id = "b4531ee9-9477-4262-8e18-00b60369352a";
contact.LogicalName = "contact";
contact.Name = "Bacon Jones";
newOpportunity.ContactId = contact;
var jsonNewOpp = window.JSON.stringify(newOpportunity);
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/OpportunitySet",
data: jsonNewOpp,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("success");
//var getNewRecord = data["d"];
//alert("GUID: " + getNewRecord.OpportunityId);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("failure due to " + errorThrown);
}
});
Have you tried running Fiddler to receive a better error message?
The code looks fine, maybe the error is in the field names?
Is the REST endpoint throwing the same error?
Thanks,
Mario

Jsonp request using jquery to fetch bing web results

using this as a guide: http://msdn.microsoft.com/en-us/library/dd250846.aspx
can someone help me with the jquery call?
Do I actually pass in the javascript code for the callback, or just the name of the function?
BingSearch = function($bingUrl, $bingAppID, $keyword, $callBack) {
$bingUrl = $bingUrl + "?JsonType=callback&JsonCallback=" + $callBack + "&Appid=" + $bingAppID + "&query=" + encodeURI($keyword) + "&sources=web";
$.ajax({
dataType: 'jsonp',
jsonp: $callBack,
url: $bingUrl,
success: function(data) {
alert('success');
$callBack(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus);
}
});
};
Update
Ok so I changed this to:
BingSearch = function(bingUrl, bingAppID, keyword, callback) {
var url = bingUrl + "?method=?&JsonType=callback&Appid=" + bingAppID + "&query=" + encodeURI(keyword) + "&sources=web";
$.getJSON(url, callback);
};
Calling it like:
BingSearch(url, appid, searchkeyword, function(searchresults) {
alert('yes!');
};
Still getting the 'invalid label' error.
To use do jsonp with jQuery, replace the JsonCallback=UserCallback with JsonCallback=?. jQuery will then handle it like a regular $.ajax() request.
I suggest starting out with $.getJSON() to get used to the Bing API and moving back to $.ajax() when your ready to integrate it with your application.
Using the example from the Bing API docs:
var apikey = 'YOUR_API_KEY';
var url = 'http://api.bing.net/json.aspx?AppId='+apikey+'&Version=2.2&Market=en-US&Query=testign&Sources=web+spell&Web.Count=1&JsonType=callback&JsonCallback=?';
$.getJSON(url, function(data) { console.log(data); });
jsonp: needs to be set to a string (I think it can also be left out), as this is just the name of the dynamically created function used to receive the JSONP.
But the formal parameter $callBack needs to be a reference to a function, so either you use
function callback(result){ /*processResultHere*/ }
BingSearch(..,..,.., callback);
or
BingSearch..,..,.., function(result){ /*processResultHere*/ });
And just so you know it, the excessive use of $ really hurts my eyes :)
Also, function names beginning with a capital should be reserved for 'classes', as many syntax checkers will complain on functions with capitals being called without new in front..

Save temporary Ajax parameters in jQuery

I am developing a heavily scripted Web application and am now doing some Error handling. But to do that, I need a way to access the AJAX parameters that were given to jQuery for that specific AJAX Request. I haven't found anything on it at jquery.com so I am asking you folks if you have any idea how to accomplish that.
Here is an example of how I want to do that codewise:
function add_recording(filename) {
updateCounter('addRecording','up');
jQuery.ajax({
url: '/cgi-bin/apps/ajax/Storyboard',
type: 'POST',
dataType: 'json',
data: {
sid: sid,
story: story,
screen_id: screen_id,
mode: 'add_record',
file_name: filename
},
success: function(json) {
updateCounter('addRecording','down');
id = json[0].id;
create_record(id, 1, 1, json);
},
error: function() {
updateCounter('addRecording','error',hereBeData);
}
})
}
hereBeData would be the needed data (like the url, type, dataType and the actual data).
updateCounter is a function which updates the Status Area with new info. It's also the area where the User is notified of an Error and where a Dismiss and Retry Button would be generated, based on the Info that was gathered in hereBeData.
Regardless of calling complete() success() or error() - this will equal the object passed to $.ajax() although the values for URL and data will not always be exactly the same - it will convert paramerters and edit the object around a bit. You can add a custom key to the object to remember your stuff though:
$.ajax({
url: '/',
data: {test:'test'},
// we make a little 'extra copy' here in case we need it later in an event
remember: {url:'/', data:{test:'test'}},
error: function() {
alert(this.remember.data.test + ': error');
},
success: function() {
alert(this.remember.data.test + ': success');
},
complete: function() {
alert(this.remember.data.url + ': complete');
}
});
Of course - since you are setting this data originally from some source - you could rely on the variable scoping to keep it around for you:
$("someelement").click(function() {
var theURL = $(this).attr('href');
var theData = { text: $(this).text(); }
$.ajax({
url: theUrl,
data: theData,
error: function() {
alert('There was an error loading '+theURL);
}
});
// but look out for situations like this:
theURL = 'something else';
});
Check out what parameters you can get in the callback for error.
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
You can use the ajax complete event which passes you the ajaxOptions that were used for the request. The complete fires for both a successful and failed request.
complete : function (event, XMLHttpRequest, ajaxOptions) {
//store ajaxOptions here
//1 way is to use the .data on the body for example
$('body').data('myLastAjaxRequest', ajaxOptions);
}
You can then retireve the options using
var ajaxOptions = $('body').data('myLastAjaxRequest');

Categories