Implement response header in Ajax call - ajax

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.

Related

Jquery AJAX call requires authentification

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

Plivo SDK call Recording

I am getting an error that i dont understand an cannot find any helpfull informations about:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https:*******' is therefore not allowed access. The response had HTTP status code 401.
function RecordTheCall()
{
var key = '*******************';
$.get( "https://api.plivo.com/v1/Account/"+key+"/Call/?status=live", function( data ) {
var callUuid = data.call_uuid
});
$.ajax({
url: "https://api.plivo.com/v1/Account/"+key+"/Call/"+callUuid+"/Record/",
type: "POST",
data: { 'auth_id': auth_id, 'call_uuid': CallUUID },
dataType: "json",
success: function (res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
}
Call recording cannot be accomplished from the Web SDK directly. You cannot use the Plivo API from your Web browser using Javascript because cross-domain ajax requests are not allowed in browsers for security reasons.
This has been explained in this Wikipedia article. There are some work arounds to overcome this, but it is browser dependent and hence it might not work always. Instead you should use the Plivo XML/API in you application.

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

406 Error when returning JSON object – Unexpected content

A few colleagues and I have a problem whereby the response from an ajax call returns some unexpected content. Rather than getting a simple JSON object back with various properties, the value of result.responseText is the HTML markup of a generic 406 status error page, saying the MIME type is not accepted by the browser.
The call is made like so:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.promotion_banner .loader').hide();
$('.promotion_banner').html(result);
},
error: function (result) {
var obj = result.responseText;
if (obj.isRedirect) {
document.location = obj.redirectUrl;
}
else {
$('.promotion_banner .loader').hide();
$(".error-wrapper").removeClass("hidden");
var generic_error = document.getElementById('generic_error').value;
$(".error-wrapper p").html(generic_error);
}
},
beforeSend: function() {
$('.promotion_banner .loader').show();
}
});
The controller response to the call is like so:
Response.StatusCode = (int)HttpStatusCode.NotAcceptable; // 406
return Json(new { errorMessage = LocalErrorMessages.Website_Promotions_FreeFiver_General_Problem, isRedirect = false } );
We would expect result.responseText to contain key values for errorMessage and isRedirect, but they’re not there.
It’s worth pointing out that this code is multi-tenanted, shared by the current application and another one, where it works absolutely fine.
We’ve tried:
- Configuring IIS to show detailed error responses rather than a custom page for more detail – gives us nothing extra towards solving the problem.
- Allowing all response content types to the call
- Changing the culture of our site (which is currently es-ES)
- Various web.config tweaks
Has anyone ever had this problem?
Simplify your request. Maybe something like:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: 'GET',
data: {foo:'bar', one:'two'},
dataType: 'json',
success: function (result) {
console.dir(result);
},
error: function (xhr) {
console.dir(xhr)
}
});
And post the response from the server. This kind of error seems a request problem rather than server configuration issue

crossdomain $.ajax and 404 error

I want to retrieve some data using $.ajax from the external ASP.NET MVC site (in this case - from my site). The code below geive me a 404 Not Found error (of course the url is valid.
But, if I change the url from url: 'http://myurl.com/Home/GetMyCode/?id=mycode' to url: 'http://localhost:123/Home/GetMyCode/?id=mycode' everything is fine. So, how to fix it ?
$.ajax({
url: 'http://myurl.com/Home/GetMyCode/?id=mycode',
type: 'POST',
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (res) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
...
}
});
[HttpPost]
public JsonResult GetMyCode(string id)
{
try
{
return Json(new { result = "ok", resultData = "OK") });
}
catch (Exception e)
{
return Json(new { result = "error", resultData = "An error occured" });
}
}
Two Methods for Handling Cross-Domain Ajax Calls:
JSONP: The Current Standard for Cross-Domain Access
JSONP is a convention used by some sites to expose their content in a way that makes it easier for callers to consume data via script, even from an external domain. The trick consists in having the site return some JSON content not as a plain string but wrapped up in a script function call. For more details..
http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
http://www.jquery4u.com/json/jsonp-examples/
Cross-origin resource sharing (CORS)
To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;
You just tell jQuery that you're in an environment where Cross-Domain XHR requests are possible.
In order to retrieve data crossdomain, you probably need to use 'jsonp'
Looks like it might be a DNS issue. Are you able to get to: http://myurl.com ?
Is the .com domain you are trying to access publicly accessible? Or is it a loopback to localhost?
that tutorial worked for me, I had to implement the JSONP handling in my MVC project. http://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm

Resources