Jquery AJAX call requires authentification - ajax

I'm trying to use the google chart api in an XPages application.
I'm using the code example given by the documentation : https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file
I have to replace the call to the php page by a call to an LS agent.
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
So my code goes to :
var jsonData = $.ajax({
url: "http://server/database/agent?openagent",
dataType: "json",
async: false
}).responseText;
On my local domino server, it works fine.
On the production domino server, I get nothing. The chart is not drawn. After debugging the js client side, it seems the ajax call is expecting an authentification even if I had to log in before.
The anonymous access is not allowed on both servers.
The security level seems to be same on both environments
Any help will be welcome (or any other way to proceed if I'm wrong).
Thank you

If you are able to draw the google chart in your local server, but not in production server, this means it is your server issue.
You can add authentication header in your jquery ajax call to make authenticated ajax request
$.ajax({
headers: {
"Authorization": "Bearer <TOKEN HERE>"
}
})
You can also send username and password in jquery ajax call, to make authenticated request. Here is the sample code from the link
$.ajax({
type: 'GET',
url: 'url',
dataType: 'json',
//whatever you need
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth(user, password));
},
success: function () {});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}

at the end, I tried to run the ajax request through dojo instead of Jquery.
My codes became this one :
var jsonData = dojo.xhrGet({
url: "http://server/database/agent?openagent",
handleAs:"json",
...
})
I did no changes at the security level or anything else.
I do not understand why the jquery syntax is not working as well the dojo syntax.
anyway, it is working now.
Many thanks to all for your suggestions

Related

How to show AJAX response message in alert?

I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything..
I have written like this-
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
TL;DR: I guess the problem is on the server side of your code (that we don't know yet).
At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.
Please try yourself using the URL: http://ip.jsontest.com/.
So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:
jsonCallback({'someResponseKeys': 'someResponseValue'});
Note: The header should contain Content-Type:application/javascript!
BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:
Don't set async to false, at the documentation of jQuery.ajax() says:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous
operation.
You don't need to set a jsonpCallback, because jQuery will generate and handle (using the success function a random one for you. Quote from the docs:
This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
So here comes my code:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
A working example can be found here.
Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallback explicitly to the function that should be called.
if you see the response in Fiddler, it seems that the issue is in the callback function.
you are doing a jsonP call - which means that you need a callback function to "read" the response data.
Do you have a local function that calls "jsonCallback"?
this is a simple jsonP request, which initiates the function "gotBack()" with the response data:
function gotBack(data) {
console.log(data);
}
$.ajax({
url: 'http://test.xyz.com/login' + '?callback=?',
type: "POST",
data: formData,
dataType: "jsonp",
jsonpCallback: "gotBack"
});
You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"
success: function (resdata) {
alert(resdata);
alert(JSON.stringify(resdata));
},
And the better option to debug the code using "debugger;"
success: function (resdata) {
debugger;
alert(resdata);
alert(JSON.stringify(resdata));
},

How to send and retrieve cross-domain ajax data in userscript

I use this code to store and retrieve ajax data via http://openkeyval.org/
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify([123,456]),
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
$.ajax({ /* retrieve data */
url: "http://api.openkeyval.org/test-key-data",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
everything work fine in Chrome javascript console but in userscript I get error like this
Uncaught ReferenceError: jQuery110208458673823624849_1375932537303 is
not defined
I try to use GM_xmlhttpRequest to retrieve data like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data",
onload: function(response) {
console.log(response.responseText);
}
});
but it seem like openkeyval doesn't accept data via POST/GET method and log result was like when you access it directly from url of browser like this
{"error":"not_found","documentation_url":"http://openkeyval.org/"}
I include jQuery and it work fine with this code
// #require http://code.jquery.com/jquery-latest.min.js
I try to use Greasemonkey/jQuery XHR bridge with out change other code by like this
// #require http://courses.ischool.berkeley.edu/i290-4/f09/resources/gm_jq_xhr.js
and try use openkeyval official javascript library with code like this
// #require http://cdn.openkeyval.org/statics/openkeyval.packed.js
and retrieve data with code like this
var ourCallback = function(value, key) {
console('The value of ' + key ' + is ' + value);
};
window.remoteStorage.getItem('test-key-data', ourCallback);
still got error ERROR: Unexpected string
Please help, I mess with it more than 10 hours. Thank you so much.
It look like $.ajax always trigger error event function
but GM_xmlhttpRequest can retrieve mistype data, so I try looking for dataType: "jsonp" in GM_xmlhttpRequest and I got that jsonp header content-type is "application/javascript" OR "application/json" and the first one work well.
my new code for retrieve data look like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data?nocache=" + new Date(),
headers: {
"Content-Type": "application/javascript"
},
onload: function(response) {
console.log(response.responseText);
}
});
and retrieve data using $.ajax even it always trigger error event function but it still send data.
I try both content-type on GM_xmlhttpRequest and still not work.
my code to store data look like this
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify(myVarObject),
dataType: "jsonp"
});
Add this into $.ajax({...})
crossDomain: true;
It is because by default cross domain ability is disabled. See http://api.jquery.com/jQuery.ajax/
EDIT:
Sometimes there will be a issue with different charset between local script and remote script. Try using:
scriptCharset: "utf-8";
Also look at JQuery AJAX is not sending UTF-8 to my server, only in IE
Elaborating my comment
The reference is to the callback function generated by jquery.
It Sounds to me the way you invoke your userscript unloads the jquery functions before the callback is executed.
Perhaps you use a link and forgot the preventDefault?
If you ajax and have
$("#linkid").on("click"
or
$("#formid").on("submit"
it is MANDATORY to continue like this:
,function(e) {
e.preventDefault();
Otherwise the link is followed or the form is submitted which may not have any visible effect, but the asynchronous scripts have been (partially) unloaded unless the form and link has a target other than the current window

Implement response header in Ajax call

Below is a cross-domain call I'm trying to make via an Ajax call. The web service we're using only returns XML, so I cannot use jsonp as a dataType. As I have it written below, I receive the following error in Chrome's debugger:
Uncaught ReferenceError: Request is not defined
Here is the code:
function GetProgramDetails() {
var URL = "http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,\'" + $('.searchbox').val() + "\')";
var sourceDomain = Request.Headers["Origin"];
var request = $.ajax({
type: 'POST',
beforeSend: function(request){
request.setRequestHeader("Access-Control-Allow-Origin", sourceDomain)
},
url: URL,
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: XMLHttpRequest,
success: function (data) {
console.log(data);
alert(data);
},
error: function (data) {
console.log(data);
alert("Unable to process your resquest at this time.");
}
});
}
EDIT
I've tried the following versions of this code and haven't seen anything different in the error message. This is being used in an enterprise environment, so is it possible that, due to security features on the server, it is not possible for this to work? I'm brand new to Ajax, so I don't know if this is something that works 100% of the time or just in a majority of settings.
beforeSend: function (request) {
request.setRequestHeader("Access-Control-Allow-Origin: *")
},
beforeSend: function (request) {
request.setRequestHeader("Access-Control-Allow-Origin: ", "http://localhost:55152")
},
beforeSend: function (request) {
request.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:55152")
},
beforeSend: function (request) {
var sourceDomain = request.Headers["http://localhost:55152"];
request.setRequestHeader("Access-Control-Allow-Origin: ", sourceDomain)
},
beforeSend: function (request) {
var sourceDomain = location.protocol + '//' + location.host;
request.setRequestHeader("Access-Control-Allow-Origin: ", sourceDomain)
},
This is your problem: var sourceDomain = Request.Headers["Origin"]; You have not defined Request with a capital R.
The meat of your problem is going to be in the cross-domain request. This is possible and you're on the right track but Access-Control-Allow-Origin is something that's set on the server as a response header, not something that's sent by the client through XHR as a request header. See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin
See the HTML5 Boilerplate .htaccess as an example of how to set this up on Apache https://github.com/h5bp/html5-boilerplate/blob/master/.htaccess and note the browser limitations https://www.bionicspirit.com/blog/2011/03/24/cross-domain-requests.html - notably that this doesn't work in IE7 and that IE doesn't support wildcards *.
Trying to mimic jsonp (returning executable JavaScript code from the server) may be possible with some clever coding but this would be more difficult - Using JSONP when returning XML
Also, if the data is sensitive then you might not want to do any sort of cross-domain request without a private key scheme since I'm not sure if the origin request header can be spoofed. The alternative would be to set up a connection for your websites to share data on the back-end rather than the front-end.
Also, JavaScript function names are not capitalized unless they are constructors.
beforeSend: function(request){
var sourceDomain = request.Headers["Origin"];
request.setRequestHeader("Access-Control-Allow-Origin", sourceDomain)
},
You were attempting to access the request before it was created, thus throwing the undefined error. The request is the jqXHR object which is passed to the beforeSend() callback function.

Basic Authentication and jQuery/ajax call

I would like to call OData .NET web service that authenticates users via basic authentication.
I use following ajax call:
var fullUri = APIUri + "?$format=json";
$.ajax({
url: fullUri,
contentType: "application/json",
dataType: "jsonp",
type: 'GET',
jsonp: '$callback',
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
},
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
The results are unusable for me:
Calls are blocked because of CORS (until I will paste API url and try to load it in chrome). I tried local html file and html file uploaded to the same domain/port, but authentication fails (according to Chrome console).
Once I enter service URL into chrome address bar, I am asked to provide login name and password by Chrome. If I enter them, they are cached and used even I assign them in beforeSend. How to blocks this behavior?
I've tried a lot of examples how to configure jsonp, headers etc, but did not find working solution yet.
IIS server response header is also configured using "Access-Control-Allow-Origin" value="*".
You can set the HTTP Password and Username in the AJAX Call directly:
$.ajax({
url: fullUri,
contentType: "application/json",
username: <login>,
password: <password>,
...
Use the following to support CORS:
jQuery.support.cors = true;
Regarding the call, are you using HTTPS? Is the certificate valid?

Gravatar VS JQuery Ajax... help?

I want to include a function on my page, that checks whether the user has a Gravatar account with their email. If yes, they should have that picture displayed, if not they should be given other options.
I'm trying to do this as follows:
$.ajax({
url: 'https://secure.gravatar.com/' + md5(user.email) + '.json',
method: 'GET',
timeout: 4000,
success: function successFn() {
doGravatarStuff();
},
error: function errorFn(response, status, error) {
console.log(response.status); //debug
}
});
This always returns an error status of 0 on Internet Explorer and I can't seem to figure out why. I tried changing the 'dataType' to 'json', 'html' etc but that doesn't seem to help.
Also, and maybe that is a related problem, if I test this on FF or Crome, with a user that really doesn't have an account, it returns a 404-error according to the 'net' tab readout
404 Not Found 649ms
but 'response.status' still seems to be 0
Any ideas anyone? Thanks so much in advance!!
Normally cross-domain AJAX requests are denied because it's a security thing. See this blog article: http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
Did you try the jsonp dataType? I use jsonp when I access twitter's tweet json feed.
Example:
var urls = "http://twitter.com/status/user_timeline/" + username + ".json?count=" + pageSize + "&page=" + currentPage;
$.ajax({
beforeSend: function () {
$("#ajax-load").fadeIn()
},
url: urls,
cache: true,
type: 'GET',
dataType: 'jsonp',
success: twitterCallback2
});
};

Resources