Hy
I need to find the current user from my SharePoint.
I have tried many things :
SP.Utilities.PrincipalInfo.get_loginName()
_spPageContextInfo.userId
...
At all times, I have the same result Undefined =(
When using CSOM API to retrieve current user object,wrap your code inside
SP.SOD.executeOrDelayUntilScriptLoaded method to make sure that the specified code is executed after SharePoint JS library (sp.js) is loaded:
SP.SOD.executeOrDelayUntilScriptLoaded(function(){
//your code goes here..
}, 'sp.js');
How to retrieve current user object using CSOM API
function getCurrentUser(success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var currentUser = web.get_currentUser();
ctx.load(currentUser);
ctx.executeQueryAsync(function(){
success(currentUser);
},
error);
}
Usage
SP.SOD.executeOrDelayUntilScriptLoaded(function(){
getCurrentUser(
function(currentUser){
console.log(currentUser.get_loginName());
},
function(sender, args)
{
console.log('Request failed ' + args.get_message() + ':'+ args.get_stackTrace());
});
}, 'sp.js');
The answer is probably here. The only thing i changed is getting LoginName instead of Title:
https://stackoverflow.com/a/21002895/1680288
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.LoginName;
alert(loginName);
}
function onError(error) {
alert("error");
}
If you are getting undefined.. Maybe you are not authenticated or did not include some relevant javascript files in your master page.
Without jquery:
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
function createXMLHttp() {
//If XMLHttpRequest is available then using it
if (typeof XMLHttpRequest !== undefined) {
return new XMLHttpRequest;
//if window.ActiveXObject is available than the user is using IE...so we have to create the newest version XMLHttp object
} else if (window.ActiveXObject) {
var ieXMLHttpVersions = ['MSXML2.XMLHttp.5.0', 'MSXML2.XMLHttp.4.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp', 'Microsoft.XMLHttp'],
xmlHttp;
//In this array we are starting from the first element (newest version) and trying to create it. If there is an
//exception thrown we are handling it (and doing nothing ^^)
for (var i = 0; i < ieXMLHttpVersions.length; i++) {
try {
xmlHttp = new ActiveXObject(ieXMLHttpVersions[i]);
return xmlHttp;
} catch (e) {
}
}
}
}
function getData() {
var xmlHttp = createXMLHttp();
xmlHttp.open('get', requestUri , true);
xmlHttp.setRequestHeader("Content-Type", "application/json;odata=verbose");
xmlHttp.setRequestHeader("accept", "application/json;odata=verbose");
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
var data = JSON.parse(xmlHttp.responseText);
var loginName = data.d.LoginName;
alert(loginName);
} else {
}
} else {
//still processing
}
};
}
getData();
Related
So I have used the below function to detect an ajax call.
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==1){
alert('server connection established');
}
if(realXHR.readyState==2){
alert('request received');
}
if(realXHR.readyState==3){
alert('processing request');
}
if(realXHR.readyState==4){
alert('request finished and response is ready');
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
It is working but now I need the url of that particular ajax request. I have functions like below:-
function loadFundSimulation(num_days = ''){
var url = "<?php echo site_url('investment_plan/simulation/FUND'); ?>";
$.post(url, data).done(function (response,status,xhr) {
#....code....#
}).fail(function (data) {
#....code....#
});
}
When the ajax is being called at that time I want url of this functions. I have many functions like this. When I get the url I want to append ?debug = 1 at the end of the url. I have tried alert(this.url); but it was returning undefined. Any help will appreciated. Thanks in advance.
Edit
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
this.addEventListener("readystatechange", function(event) {
if(this.readyState == 4){
var self = this;
var response = {
method: method,
uri: uri,
responseText: self.responseText
};
response.uri = uri + '?debug=1';
console.log(response);
} else {
console.log(this.readyState);
}
}, false);
open.call(this, method, uri, async, user, pass);
};
I have got the url of that ajax request and I appended ?debug=1 as well. When I console.log(response); I see the url is being changed but I still don't see any error. Please let me know I have to do anything else for that.
After searching a lot this is the best way to do this. Though only tested on chrome.
(function() {
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
arguments[1] = arguments[1] + '&debug=1';
console.log( arguments[1] );
return proxied.apply(this, [].slice.call(arguments));
};
})();
I try to fetch Json object from URL.The following codes doesnt work, They didnt gave me an error or they didnt return me something
I can get Json result by viewing url in chrome.So there is no mistake in url name.
Code 1:
<script type="text/javascript">
var url = "http://....; //I cant write url bcz of privacy reasons.
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://fantasy.premierleague.com/web/api/elements/100/').then(function (data) {
alert('Your Json result is: ' + data.result);
var o = JSON.parse(JSON.stringify(data));
window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
// document.getElementById("avengers").innerHTML = o.provider[1].agentID+ " " + o.provider[1].nodeID;
// document.getElementById('avengers').innerHTML = o.result;
console.log(o);
}
//var names = o.proviver[0].agentID.toString();
//you can comment this, i used it to debug
}, function (status) { //error detection....
alert('Something went wrong.');
});
</script>
Code 2 :
$.ajax({
type: "GET",
url: '......',
dataType: 'json',
success: function(response){
console.table([response]);
// $('avengers').append(response.result)
}
});
Are there any other way. Or I am completely wrong.
$.post(url,
data={"key1":value1,"key2":value2,....}, //data={} if nothing to post
function(data,status)
{
if(status=="success")
{
console.log(data)
}
else
{
alert('fail')
}
}
I am developing an extension for Mozilla Firefox, where I override the native listener with my own and monitor all HTTP requests, as shown in the post here:
http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/
I monitor those requests that reside under a specific domain and change their corresponding response body, with the response body I receive from my own XMLHTTPRequest. For text files, everything is working fine.
However, I face a problem while downloading images. For some reason, when I write the incoming data to the stream and then, try to open the image, I get the error that the image contains errors and cannot be displayed.
What am I possibly doing wrong?
Update: I provide some code, in order to clarify my approach.
var xmlRequest = Cc['#mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Ci.nsIXMLHttpRequest);
...
xmlRequest.open('GET', xmlRequestURL, false);
xmlRequest.send(null);
function TracingListener() {}
TracingListener.prototype = {
originalListener: null,
onStartRequest: function (request, context) {
httpChannel = request.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
try {
this.originalListener.onStartRequest(request, context);
}
catch (ex) {
request.cancel(ex);
}
},
onDataAvailable: function (request, context, inputStream, offset, count) {
httpChannel = request.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
//Read the contents from the stream, but ignore them.
var binaryInputStream = CCIN('#mozilla.org/binaryinputstream;1', 'nsIBinaryInputStream');
binaryInputStream.setInputStream(inputStream);
var binaryOutputStream = CCIN('#mozilla.org/binaryoutputstream;1', 'nsIBinaryOutputStream');
var data = binaryInputStream.readBytes(count);
//Delay the call to the original listener.
},
onStopRequest: function (request, context, statusCode) {
httpChannel = request.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
//Check if the response is successful.
if(xmlRequest.status == 200) {
try {
var responseLen = xmlRequest.getResponseHeader("Content-Length");
var response = xmlRequest.response;
var storageStream = CCIN('#mozilla.org/storagestream;1', 'nsIStorageStream');
storageStream.init(8192, responseLen, null);
var binaryOutputStream = CCIN('#mozilla.org/binaryoutputstream;1', 'nsIBinaryOutputStream');
binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));
binaryOutputStream.writeBytes(response, responseLen);
//Make the call to the original listener.
this.originalListener.onDataAvailable(request, context, storageStream.newInputStream(0), 0, responseLen);
}
catch (e) {
dumpError(e);
}
//Pass it to the original listener
this.originalListener.onStopRequest(request, context, statusCode);
}
else {
console.log('[INFO] onStopRequest not processed, status is ' + xmlRequest.status + ', for URL: ' + requestURL);
}
}
}
var observer = {
httpRequestObserver: {
observe: function (request, aTopic, aData) {
httpChannel = request.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
if(mustBeMonitored(requestURL)) {
console.log('[INFO] Observing URL: ' + requestURL);
if (aTopic == 'http-on-modify-request') {
console.log('[INFO] ' + aTopic + ' for URL: ' + requestURL);
var newListener = new TracingListener();
request.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = request.setNewListener(newListener);
}
}
},
register: function () {
observerService.addObserver(observer.httpRequestObserver, 'http-on-modify-request', false);
},
unregister: function () {
observerService.removeObserver(observer.httpRequestObserver, 'http-on-modify-request');
},
QueryInterface: function (aIID) {
/*if (typeof Cc == "undefined") {
var Cc = components.classes;
}
if (typeof Ci == "undefined") {
var Ci = components.interfaces;
}*/
if (aIID.equals(Ci.nsIObserver) || aIID.equals(Ci.nsISupports))
return this;
throw components.results.NS_NOINTERFACE;
}
}
};
Finally, I was able to detect the problem. For the XMLHttpRequest, I had to specify its response type as follows:
xmlRequest.responseType = 'arraybuffer';
Then, the response was stored in a JavaScript ArrayBuffer, which I had to transform into a Uint8Array and then, store it into the stream.
This solution applies for both binary and text files.
I'm new to javascript which should be really simple to solve, but I am lost as of now.
I have a url: http:getall.json
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:
request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
your result will be in the data variable.
JSONP calls:
function getJSONP(url, callback) {
var script = document.createElement('script');
var callbackName = "jsonpcallback_" + new Date().getTime();
window[callbackName] = function (json) {
callback(json);
};
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
//jsonObject is what you want
});
Regular ajax ajax call:
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
function getJSON(url, callback) {
req = getXHR();
req.open("GET", url);
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObject = null,
status;
try {
jsonObject = JSON.parse(req.responseText);
status = "success";
} catch (e) {
status = "Invalid JSON string[" + e + "]";
}
callback(jsonObject, status, this);
}
};
req.onerror = function () {
callback(null, "error", null);
};
req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
//jsonObject is what you want
});
I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource
with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:
A PHP Error was encountered
...
In your HTML include your json file and a js code as modules
<script src="/locales/tshared.js" type="module" ></script>
<script src="/scripts/shared.js" type="module" ></script>
file content of tshared
export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;
Adapt path and names as needed, use locale at will.
I try to make Cross Domain POST requests and get back JSON encoded responses,
everything works fine except in IE 7, 8, 9.
I have try those solutions but i get this error:
Object doesn't support property or method 'setRequestHeader'
Function createXMLHTTPObject() - attempt 1
function createXMLHTTPObject() {
var xmlhttp = false;
var is_IE = window.XDomainRequest ? true : false;
if (is_IE) {
xmlhttp = new window.XDomainRequest();
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
Function createXMLHTTPObject() - attempt 2
var XMLHttpFactories = [
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject("Msxml2.XMLHTTP") },
function() { return new ActiveXObject("Msxml3.XMLHTTP") },
function() { return new ActiveXObject("Microsoft.XMLHTTP") }
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0; i<XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch(e) {
continue;
}
break;
}
return xmlhttp;
}
Function send()
Here it returns the error, at: req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
function send(postData, callback) {
var url = 'http://domain.com/ajax-processing.php'; //url overlap
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method, url, true);
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
if (postData) {
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
console.log('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
Here i call the send function
var insert = 'id=1&type=insert';
CLib.send(insert, function(data) {
console.log(data);
});
Is it possible to make Cross Domain requests in IE?
How i can leave behind this part, without using any other library like jQuery?
Thanks a lot #Esailija who inform me that i can't make set request headers with the XDomainRequest.
So i tried other methods and solutions also and i finally came back with a simpler method:
changed the POST requests to GET and everything working fine after some small changes.