I'm relatively new to Ajax and was just tasked with this cross-domain call. We have a text box on our web page that a user will use to preform a search of company names. By clicking a button next to the text box, the Ajax call will be requested. Unfortunately the web service is located in a separate domain, so this is naturally causing issues.
Below is my best attempt at making this work. I should also note, the purpose of this call is to return the results in an XML format, which will be parsed in the success portion of the request.
Here is the error message again:
Origin http://localhost:55152 is not allowed by Access-Control-Allow-Origin.
I'm at a loss as to what to do for a work-around, any ideas would be greatly appreciated.
function GetProgramDetails() {
var URL = "http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,\'" + $('.searchbox').val() + "\')";
var request = $.ajax({
type: 'POST',
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.");
}
});
}
This error is due to the restriction enforced in cross-domain resource sharing. This has been implemented as a part of security feature to restrict the clients(domain) of a resource via cross domain calls. When you send a request to the webservice or api or similar, it adds Origin header in the request for the server or destination (here your api) to validate if the request is coming from an authorized source or not. Ideally the api/server should look for the Origin in the Request header it received and probably validate against the set of origins(domains) which it is permitted to serve the resources to. If it is coming from a permitted domain it will add the same domain in the response header as "Access-Control-Allow-Origin" value. wildcard is also permitted for this, but the issue is that with wild card permission any one can make a request and get it served (with some restrictions like an api is authenticated via windows auth or cookies where you need to send the withCredentials value * is not allowed). it is not a good practice to use wildcard origin the response header which makes it open to everyone.
These are some ways to set the response header with the values:-
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://yourdomain.com
you can even add multiple Access-Control-Allow-Origin headers in the same response (I believe works in most browsers)
Access-Control-Allow-Origin: http://yourdomain1.com
Access-Control-Allow-Origin: http://yourdomain2.com
Access-Control-Allow-Origin: http://yourdomain3.com
On the server side (c# syntax) you would do this:-
var sourceDomain = Request.Headers["Origin"]; //This gives the origin domain for the request
Response.AppendHeader("Access-Control-Allow-Origin", sourceDomain ); //Set the response header with the origin value after validation (if any) .Depending on the type of application you are using syntax may vary.
Hope this helps!!!
Related
I'm trying to delete file/s in uploadcare rest api using jquery ajax.
Here is my current codes for jquery:
$.ajax({
url: "http://api.uploadcare.com/files/" + $("#photoguid").val() + "/",
type: "DELETE",
contentType: "application/json"
});
My question is how to implement it properly because every time I call this, it redirects me to login page, that's what I see when checking in fiddler and I'm not sure where to put the authorization. I'm only using free trial for this.
The docs do say Rest calls must be done via https. https://uploadcare.com/documentation/rest/
As for the request headers looks like that was answered here:
How can I add a custom HTTP header to ajax request with js or jQuery?
Here is an example for your case:
$.ajax({
url: "https://api.uploadcare.com/files/" + $("#photoguid").val() + "/",
type: "DELETE",
headers: { "Authorization": "Uploadcare.Simple demopublickey:demoprivatekey" }
});
Since 2014-12-24, Uploadcare API allows cross origin requests so if you're up to exposing your private key or want to add roundtrip to your backend to get proper Authentication header value, go for it.
is it possible to post data from an html page using Jquery to another asp.net website ?
say www.site1.com/mail.html - > www.site2.com/mailServ.aspx
using jquery ajax i could use this code to post to code behind [webmethod]
so instead of code within same website(site2) it will be sent from site1
this is the code i am using to post the form data to a web method within same website application
function jQuerySendMailCsCodeBehind(resluts) {
var SentClientinfo = []
SentClientinfo.push({ key: "SentClientinfo", value: resluts });
var CurrpageURL = "default.aspx/"; <---
var WebmethodName = "StartTest";
var StageIdentifyer = "stage1";
var Post_TargetUrl = CurrpageURL + WebmethodName;
jQueryAajaxNoPostBack(Post_TargetUrl, SentClientinfo, StageIdentifyer);
}
i tried to post from outside of application
so i just used
var CurrpageURL = "http://www.site2.com/default.aspx/";
from the other site (site1) html website non asp.net but the idea did not work in reality (:
so is there an option that a webForms application/ asp.net website
will accept requests from another website code of ajax/jquery ?
By default, JavaScript is not allowed to access other domains than the one it originated from for security reasons. You don't want the JavaScripts on my site to access your bank's web site, with your bank login cookie if you happen to be looking at my site while being logged in to the bank.
One way to work around it is JsonP, but as far as I've understood it it's mostly for retrieving data.
What you're probably looking for is Cross Origin Resource Sharing or short CORS. To implement that, your site2 would need to set a Access-Control-Allow-Origin header and the users would be required to use a browser that supports CORS (not all do, see the wikipedia page for info).
You cannot make cross-website requests with javascript. You need to use jsonp
jQuery supports jsonp, see the following example
$.ajax({
type: 'GET',
url: 'http://githubbadge.appspot.com/badge/torvalds',
dataType: 'jsonp',
success: function(json) {
var result = '<h3>' + json.user.login + '</h3>' +
'<p>Languages: ' + json.languages + '</p>' +
'<p>Followers: ' + json.user.followers + '</p>';
$('#badge').append(result);
}
});
So I have the following working:
$.ajax({
type: 'POST',
url: 'user',
data: '{"FirstName":"John","LastName":"Doe"}',
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success!' + data.Id);
}
});
however this fails (which should be equivalent):
$.post('user', '{"FirstName":"John","LastName":"Doe"}');
Any idea what's wrong? Is $.post somehow incompatible with WCF rest?
No, the two are not equivalent at all. Look with FireBug, Fiddler, ... and compare the 2 requests. In the second example you are not setting the contentType: "application/json" request header. You are not setting it because the $.post method doesn't allow you to.
And the server doesn't accept your request because since you are trying to POST to a JSON enabled service, it expects the request to be JSON and of course the client to set the application/json content type request header. You are posting some string and since you don't indicate what this string represents through the content type header, the server doesn't know what to do with it and drops the request.
This is to say that you should use $.ajax as in the first example to invoke your service. Actually I'd recommend you a slight modification and instead of:
data: '{"FirstName":"John","LastName":"Doe"}',
use:
data: JSON.stringify({"FirstName":"John","LastName":"Doe"}),
This will ensure that if tomorrow you decide to deal with someone else than Mr. Jon Doe, like for example Mr. Jon O"Hara, your JSON will still be properly encoded which is what the JSON.stringify method does. It is natively built into modern browsers but if you need to support some legacy browsers you could include the json2.js script to enable it.
is it possible to send a web request from the user browser to another api and then process the result sent back??
im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
dataType: "xml",
success: function(xml) {
alert("sucess");
$(xml).find('Ip').each(function() {
var ip = $(this).find('Ip').text();
alert(ip);
});
}
});
});
Due to same origin policy restriction you are pretty limited to sending AJAX requests to your own domain only. JSONP is a common workaround but the remote site needs to support it. Another workaround consists in crating a server side script on your domain which will serve as a bridge between your domain and the remote domain and it will simply delegate the AJAX request sent to it from javascript.
Should be possible, I have done the same.
BUT you have to have the pages on the same server, you cannot send a request to another server, in that case you would have to use a proxy on your server to relay the call.
Just to add to what was already said: if you can't create your own JSONP proxy, you can use YQL service which creates that proxy for you. Note that YQL will wrap your data with it's own meta data (unless there is a way yo disable that...).
By the way, you should use JSON output instead of XML output from your API service. JSON is a more lightweight format and as such is more adapted for Web.
Below is a fully functional example with your API URL (outputting JSON this time) and YQL:
var apiRequestUrl = "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=json";
var yqlRequestUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22";
yqlRequestUrl += encodeURIComponent(apiRequestUrl);
yqlRequestUrl += "%22&format=json&callback=?";
$.getJSON(yqlRequestUrl,
function(jsonData) {
alert(jsonData.query.results.json.Ip);
});
Finally, this article can come handy: http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/
I will have a widget on a remote page. In the widget I want javascript or jquery to get all the article content from the webpage and send it back to my website. I only need just the article content and not all the other information on the webpage. I would like the script to send the remote webpage url, page content, title text, and h1 text. I would not like to receive any html tags. Is this possible to do?
The script I am making is like google adsense.
Also, Ill be using c# as my backend server
will something like this work?
http://blog.nparashuram.com/2009/08/screen-scraping-with-javascript-firebug.html
my suggestion, if it's not too much data would be to use a beacon.
var beac = new Image();
beac.onload = function () {
//do somethiringng on completion
}
beac.src = "youdomain/somthing.php?var=asdasd&key=someUniqueString";
This allows you to send a moderate amount of data to a server on another domain, provided you don't need anything back.
In short you can't do this, at least not in the way you were expecting. For security reasons there's a same-origin policy in place that prevents you from making requests to another domain.
Your best option is to do this on your server and make the request to it. I can't speak as to how you'd do this on the server since your question doesn't include which framework you're on, but let's say it's PHP, then you'd have that page take a URL, or something you can generate the URL from, then return a JSON object containing the properties you listed. The jQuery part would look something like this:
$("a").click(function() {
$.ajax({
url: 'myPage.php',
data: { url: $(this).attr("href") },
dataType: 'json',
success: function(data) {
//use the properties, data.url, data.content, data.title, etc...
}
});
});
Or, the short form using $.getJSON()...
$.getJSON('myPage.php', { url: $(this).attr("href") }, function(data) {
//use the properties, data.url, data.content, data.title, etc...
});
All the above not withstanding, you're better off sending the URL to your server and doing this completely server-side, it'll be less work. If you're aiming to view the client's page as they would see it...well this is exactly what the same-origin policy is in place to prevent, e.g. what if instead of an article it was their online banking? You can see why this is prohibited :)