I need to send data to a remote server using javascript. How do I do this?
Background info:
There's a webpage from which I extract some information using JS, and I need to send it back to another server for processing. Response is not neccesary. The data is XML, Which I've URLencode'd.
How would one do this?
EDIT
The server I'm requesting the data from is not the same that receives the data. Just to clarify.
One of the most common ways to do this is AJAX. Here's how you perform an AJAX post request using jQuery:
<script type="text/javascript">
$.post('/remote-url', {xml: yourXMLString });
</script>
On the server side you process it like any other POST request. If you're using PHP it's $xml = $_POST['xml'];
The biggest limitation of AJAX is that you're only allowed to make requests to the same domain the document has been loaded from (aka cross-domain policy). There are various ways to overcome this limitation, one of the easiest one is JSONP.
UPD. For cross-domain requests an extremely simple (though not universal) solution would be:
(new Image).src = 'http://example.com/save-xml?xml=' + escape(yourXMLString)
This will issue a GET request (which cannot exceed 2KB in Internet Explorer). If you absolutely need a POST request or support for larger request bodies you can either use an intermediate server-side script on your domain or you can post a dynamically created html form to iframe.
submit a form using POST. That is working on all browsers cross domains. Have the server process the post. the form can be submitted to a hidden frame if you want to simulate AJAX
Use Cross Domain Resource Sharing (MDC) (IE XDR)
use a web bug (create an image, set the source to the url you want - smallish GET requests only)
var img = new Image();
img.src="http://www.otherserver.com/getxml?xml="+encodeURIComponent(yourXML);
(Oops, I see Lebedev did more or less the same in his update)
use a proxy, i.e. have your server talk to the other server for you
Look into Javascript's XMLHTTPRequest method -- or start with a Google search for AJAX. There's lots of ways to do this -- including some very easy ways through JS libraries like jQuery -- but a more specific answer would require some more specifics on the specific technologies you're using.
EDIT: You can set up the AJAX request to post to a server-side script (acting as a proxy) on your own domain, and have that script turn around and post the data to your remote server.
Related
This question already has answers here:
What is JSONP, and why was it created?
(10 answers)
Closed 7 years ago.
As you know, the security of the web browser disallows making of cross domain requests. I read a book which says that you should use XMLHTTPRequest only if you can put the files on the server (means put the page you will load to the same requested domain). If you can't - you should search for an alternative.
My questions are:
What is the cross domain alternative to XMLHTTPRequest?
What about WebSockets? Does this technology allow cross domain request?
EDIT:
It still isn't clear to me...
For example, I pull my page from www.domain1.com and I need to request javascript from www.domain2.com. So the pulled page should include something like:
<script src="www.domain2.com/script.js"></script>
to avoid cross domain restrictions.
And I can use JSONP, and request will look like:
http://ww.domain1.com/?callback=someFunction.js
But: isn't it the same? I just pull js from another domain! Does it avoid cross domain restrictions?
You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.
You can find some more information and a working example here:
http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
JSONP is an alternative solution, but you could argue it's a bit of a hack.
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
Make cross-domain ajax JSONP request with jQuery
If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather).
I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.
This question already has answers here:
What is JSONP, and why was it created?
(10 answers)
Closed 7 years ago.
As you know, the security of the web browser disallows making of cross domain requests. I read a book which says that you should use XMLHTTPRequest only if you can put the files on the server (means put the page you will load to the same requested domain). If you can't - you should search for an alternative.
My questions are:
What is the cross domain alternative to XMLHTTPRequest?
What about WebSockets? Does this technology allow cross domain request?
EDIT:
It still isn't clear to me...
For example, I pull my page from www.domain1.com and I need to request javascript from www.domain2.com. So the pulled page should include something like:
<script src="www.domain2.com/script.js"></script>
to avoid cross domain restrictions.
And I can use JSONP, and request will look like:
http://ww.domain1.com/?callback=someFunction.js
But: isn't it the same? I just pull js from another domain! Does it avoid cross domain restrictions?
You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.
You can find some more information and a working example here:
http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
JSONP is an alternative solution, but you could argue it's a bit of a hack.
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
Make cross-domain ajax JSONP request with jQuery
If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather).
I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.
I know it's possible to load any kind of document from any domain from JavaScript (without necessarily being able to peek at its content), but it usually concerns regular GET requests. What about POST?
Is it possible to make an HTTP POST request from JavaScript to any domain name? (I'm specifically interested in form submissions.)
If so, how?
As per some answers on a nearby question, «HTTP GET request in JavaScript?», you might use XMLHttpRequest, since, according to the docs, the POST method is supported, too.
http://www.w3.org/TR/XMLHttpRequest/
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest
A sample code from the above w3.org document:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
However, it would seem like in order for it to work with POST requests to domains unrelated to yours (where instead of "/log", a complete http or https URL is specified), the Cross-Origin Resource Sharing may have to be supported and enabled on the target server, as per https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Simple_requests.
So, it seems like, at least through XMLHttpRequest, you cannot make form submissions through POST requests (in fact, looks like even GET requests won't fly, either).
I have to send (and receive) certain data to a server using JQuery and JSON.
Works so far, but not cross domain, and it has to be cross domain.
I looked how to solve this and found JSONP. As far as I see, using JSONP I have to send the callback and the data using GET (JQuery allows to use "POST" as method, but when I inspect web traffic I see it is sending actually GET and everyting as parameter).
JSONP also requires changes in the server, because they are expecting a POST request with JSON data, and they have to implement something to process the JSONP GET request.
So I'm wondering what's the difference between this and sending the data as key value parameters in GET request?
Is the difference the possibility to use a callback? Or what exactly?
Sorry a bit lost... thanks in advance
JSONP is not a form submission. It is a way of telling the server via a GET request how to generate the content for a script tag. The data returned is a payload of JavaScript (not just JSON!) with a function call to a callback which you (by convention) reference in the GET request.
JSONP works because it is a hack that doesn't use AJAX. It isn't AJAX and you should not confuse it for such because it does not use a XMLHttpRequest at any point to send the data. That is how it gets around the Same Origin Policy.
Depending on the browsers you have to support, you can implement Cross-Origin Resource Sharing headers on the server side which will let you use normal AJAX calls across trusted domains. Most browsers (IE8, Firefox 3.5+, etc.) will support CORS.
Another solution you can use if you don't want to use CORS or JSONP is to write a PHP script or Java servlet that will act as a proxy. That's as simple as opening a new connection from the script, copying all of the incoming parameters from your AJAX code onto the request and then dumping the response back at the end of your script.
I found an answer that worked for me with the cross-domain issue and JSON (not JSONP).
I simply used:
header('Access-Control-Allow-Origin: *');
inside my json file (file.php) and called it like this:
var serviceURL = 'http://your-domain.com/your/json/location.php'
$.getJSON(serviceURL,function (data) {
var entries = data;
//do your stuff here using your entries in json
});
BTW: this is a receiving process, not sending.
I need to make an AJAX request from a website to a REST web service hosted in another domain.
Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.
The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.
Here is the JavaScript code that makes the asynchronous call:
var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);
How can I have this work in other browsers beside Internet Explorer?
maybe JSONP can help.
NB youll have to change your messages to use json instead of xml
Edit
Major sites such as flickr and twitter support jsonp with callbacks etc
The post marked as the answer is erroneous: the iframes document is NOT able to access the parent. The same origin policy works both ways.
The fact is that it is not possible in any way to consume a rest based webservice using xmlhttprequest. The only way to load data from a different domain (without any framework) is to use JSONP. Any other solutions demand a serverside proxy located on your own domain, or a client side proxy located on the remote domain and som sort of cross-site communication (like easyXDM) to communicate between the documents.
The fact that this works in IE is a security issue with IE, not a feature.
Unfortunately cross-site scripting is prohibited, and the accepted work around is to proxy the requests through your own domain: do you really have no ability to add or modify server side code?
Furthermore, the secondary workaround - involving the aquisition of data through script tags - is only going to support GET requests, which you might be able to hack with a SOAP service, but not so much with the POST request to a RESTful service you describe.
I'm really not sure an AJAX solution exists, you might be back to a <form> solution.
The not very clear workaround (but works) is using iframe as container for requests to another sites. The problem is, the parent can not access iframe's content, can only navigate iframe's "src" attribut. But the iframe content can access parent's content.
So, if the iframe's content know, they can call some javascript content in parent page or directly access parent's DOM.
EDIT:
Sample:
function ajaxWorkaroung() {
var frm = gewtElementById("myIFrame")
frm.src = "http://some_other_domain"
}
function ajaxCallback(parameter){
// this function will be called from myIFrame's content
}
Make your service domain accept cross origin resource sharing (CORS).
Typical scenario: Most CORS compliant browsers will first send an OPTIONS header, to which, the server should return information about which headers are accepted. If the headers satisfy the service's requirements for the request provided (Allowed Methods being GET and POST, Allowed-Origin *, etc), the browser will then resend the request with the appropriate method (GET, POST, etc.).
Everything this point forward is the same as when you are using IE, or more simply, if you were posting to the same domain.
Caviots: Some service development SDK's (WCF in particular) will attempt to process the request, in which case you need to preprocess the OPTIONS Method to respond to the request and avoid the method being called twice on the server.
In short, the problem lies server-side.
Edit There is one issue with IE 9 and below with CORS, in that it is not fully implemented. Luckily, you can solve this problem by making your calls from server-side code to the service and have it come back through your server (e.g. mypage.aspx?service=blah&method=blahblah&p0=firstParam=something). From here, your server side code should implement a request/response stream model.
Just use a server side proxy on your origin domain. Here is an example: http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html
This can also be done using a webserver setup localy that calls curl with the correct arguments and returns the curl output.
app.rb
require 'sinatra'
require 'curb'
set :views,lambda {"views/"+self.name.to_s.downcase.sub("controller","")}
set :haml, :layout => :'../layout', :format => :html5, :escape_html=>true
disable :raise_errors
get '/data/:brand' do
data_link = "https://externalsite.com/#{params[:brand]}"
c = Curl::Easy.perform(data_link)
c.body_str
end
Sending an ajax request to localhost:4567/data/something will return the result from externalsite.com/something.
Another option would be to setup a CNAME record on your own domain to "Mask" the remote domain hostname.