i've recently tried to get some Response from an URL using jQuery. Therefore I copied a get request sample of jQuery API Get Request Tutorial into my project and tried to run it, but my debugging messages showed me, that it can't go further. I tried the javascript Ajax Library using a simple request, but it didn't work.
So i'm asking you, if you could help me somehow.
And this is all what i do, but there is no response.
var url = "http://www.google.com";
$.get(url, function(data){
alert("Data Loaded: " + data);
});
Did i probably forgot to include a ajax or jQuery library. For a better understanding, i have c and obj-c experince, this is why i think, that a library is missing.
In each sample there is just a short url like "test.php". Is my complete HTTP url wrong?
Thanks for your answers in advanced.
Br
Nic
I have provided an example scenario to help get you started:
<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script
This is probably best to include inside of an external JS file:
//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
$.ajax({
//The URL to process the request
'url' : 'page.php',
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type' : 'GET',
//Any post-data/get-data parameters
//This is optional
'data' : {
'paramater1' : 'value',
'parameter2' : 'another value'
},
//The response from the server
'success' : function(data) {
//You can use any jQuery/JavaScript here!!!
if (data == "success") {
alert('request sent!');
}
}
});
});
You're hitting the Same Origin Policy with regard to ajax requests.
In a nutshell, JS/Ajax is by default only allowed to fire requests on the same domain as where the HTML page is been served from. If you intend to fire requests on other domains, it has to support JSONP and/or to set the Access-Control headers in order to get it to work. If that is not an option, then you have to create some proxy on the server side and use it instead (be careful since you can be banned for leeching too much from other sites using a robot).
As others have said you can't access files on another server. There is a hack tho. If you are using a server side language (as i assume you are) you can simply do something like:
http://myserver.com/google.php:
<?php
echo get_file_contents('http://www.google.com');
?>
http://myserver.com/myscript.js
$.get('google.php',function(data){ console.log(data) });
That should work!
you just can access pages from your domain/server
Related
I apologize if this question has already been answered.
I am trying to retrieve data from a REST web service that exposes a JSON interface using jQuery .ajax call.
When I call the service using the URL, the jQuery call fails although I get a HTTP status code 200 OK.
When I copy the response into a file on the filesystem and retrieve this, the same call works.
Both the file I am accessing and the web service I am calling are on the same machine.
Some notes on the url used in the code below:
Using:
url: "http://localhost:9090/app/user/861",
the call fails, goes into .fail on all browsers.
The URL itself returns the json on all browsers:
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
when using "test.json" in the local filesystem following is the behavior:
url: "ajax/test.json",
On Firefox, the call executes, goes into .done and displays the result on page.
On Chrome, the call fails with status 404 and the following message -
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I tried different combinations changing dataType:"jsonp", adding a ?callback=? to the end of the URL, and enclosing the data in the test.json with a '(' and a ')' without luck.
Please understand I am new to UI programming, javascript and jQuery.
Please help with what I am doing wrong. Here's the javascript:
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url:"ajax/test.json",
// the following commented call fails, goes into .fail
// url:"http://localhost:9090/app/user/861",
contentType: "application/json",
accepts: "application/json",
dataType: "json"
})
.done(function(data) {
alert("Success");
console.log(data);
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
})
.fail(function(data) {
console.log(data);
alert("Failed");
})
.always(function() {
alert("In Always");
});
});
</script>
The following is the output when I paste the url into the browser (also the contents of ajax/test.json):
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
Your problem is not about UI programming, it's about the security model of modern browsers :p
Access-Control-Allow-Origin errors occurs when you call a webservice (ie: load a JSON file) from a domain that is different from the one hosting your HTML page.
In your case, you are opening the html file from your hard drive (file:///) and calling a webservice on localhost.
This is a security feature in all modern browsers that forbid getting data from a foreign webservice without the webservice owners authorizing you (or everyone, wildcards are allowed) to call it.
I recommend reading the following guide from MDN, so that you understand WHY you are having this problem.
It will then be easy to resolve
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
If you control the source code of the webservice, or the webserver hosting it, you need to add Access-Control-Allow-Origin HTTP headers.
Do you make your ajax call using Apache on wamp, lamp, xampp or mamp or not? I think you work directly using some files lets say on your desktop and not from the www file of wamp. If the browser sends a correct url then the backend responds great, your frontend code seems fine so i think chrome complains about your not using localhost. Am i right? Whats your local development setup?
If it's a local file on the client-side, use file:/// to prefix the URL:
url: 'file:///ajax/test.json'
The third / in file:/// indicates:
As a special case, can be the string "localhost" or the empty
string; this is interpreted as `the machine from which the URL is
being interpreted'.
3.10
Reference here
Download a tool called fiddler, from http://fiddler2.com/ great way to debug web requests and to see why they are failing.
This will help you narrow down the issue you are experiencing and we can help you further because currently its all guess work.
I had the same issue, all worked fine in I.E and FireFox, a had one ajax call to a rest service using jsonp and it worked fine in chrome, however when I tried to load a file using jsonp I got the cross domain error. In short i had to add "file:" to my file path in the url
$.ajax({
type : 'GET',
url : 'file:jsondata/rain_acc_data.json',
dataType : 'jsonp',
jsonpCallback : "jsoncallback",
success : function(data) {
aler('ok');
},
error : function(jqXHR, status) {
alert("Failed to load list" + status + jqXHR);
}
});
this worked for me, make sure to wrap your json in the file with jsoncallback("your jason here");
I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers
Setup is I have one Rails app setup to act as an JSON API and another static html page that I want to use to call the API. For sake of argument the rails API is at foo.com and the static html page is at bar.com.
On the foo.com app I have something like this:
if !cookies[:foo]
cookies[:foo] = "testing #{rand(500)}"
else
logger.info(cookies[:foo])
render :json => { :cookie => cookies[:foo] }
When I try to do a ajax GET request with jquery from bar.com the cookie does not get sent back to the JSON API.
$.get('http://foo.com/', function(data){console.log(data)})
But If I load the page a resource I can get the cookies to send back and forth between foo.com and bar.com
<script type="text/javascript" src="http://foo.com"></script>
Does anyone know why I am able to pass cookies back and forth cross-domain when loading the script as a script resource and not when I do a simple ajax request? Any way around this?
Use $.ajax as you need to make a JSONP request coz your ajax call is cross site.
$.ajax({
url: "xxxx",
crossDomain : true,
dataType : 'json',//if response is in JSON Notation
success : function (result){
alert(result);
}
});
Just as techie said, you need to use $.ajax and make a json(p) request in order for cross domain to be enabled.
Cookies are tricky with this sort of implementation though. even if you manage to send your cookies back and forth using some sort of hack, older (or cheaper) browsers will block them.
*cough* IE *cough*
A simple way to "hack" around this is to pass the cookie in the url, like so:
$.ajax({
url: "//domain.com/path/to/stuff;cookie1=value1?someParameter2=value2",
crossDomain : true,
dataType : 'json',//if response is in JSON Notation
success : function (result){
alert(result);
}
});
In this example, I've told my server that my request has a cookie name "cookie1" with a value of "value1" and a GET parameter with a value of "value2"
Hope this helps.
Looking to place a button that triggers a simple SMS script on my Tropo account using jQuery and an Ajax get request. The button does not need to open anything, but simply trigger the Tropo script (JS) to send an SMS.
The URL with token given on Tropo is: http://api.tropo.com/1.0/sessions?action=create&token=foo
The about URL when triggered send an SMS saying: "Dinner's ready".
I have a button in html: Dinner
In my HTML I'm linked to an external js:
$("#myButton").click( function(e) {
e.preventDefault();
$.get("http://api.tropo.com/1.0/sessions?action=create&token=foo", function( data ) {
console.log( data );
});
});
This does not succeed, and does not fire any console errors. Would love some insight.
I think you are trying to get data from a cross-domain service, according to same origin policy you can't do so. You can try like this:
$("#myButton").click( function(e) {
e.preventDefault();
$.ajax({
url: 'http://api.tropo.com/1.0/sessions?action=create&token=foo',
dataType: 'jsonp',
success: function(data) {
console.log( data );
}
});
});
As already mentioned this is probably an issue with getting data from a cross domain service. JSONP would get around this but I am not sure that Tropo's API will work with JSONP. I could not find any mention of it in the docs or user forum. If JSONP does not work then you will need to send a message to the server and use some server-side code to call Tropo's WebAPI to send the SMS message.
So i have a json file named array.json on my web-server i intend to read this file in my web-application locally (for now) and then on a different domain once i go live, i have created this json file myself and here is the data it contains.
{"h1": "cmPanel", "h2" : "cmAuto", "h3": 0}
When i am trying to read the file I am not getting back a response, why would this be?
Here is my code for reading the file;
$.getJSON('http://www.foobar.com/array.json', function(data){
alert(data);
});
I have also tried adding &callback=? and still i receive nothing, could you please assist !
Quoting official docs:
Due to browser security restrictions, most "Ajax" requests are
subject to the same origin policy; the request can not successfully
retrieve data from a different domain, subdomain, or protocol.
Script and JSONP requests are not subject to the same origin
policy restrictions.
More info about Same Origin Policy
To work around it, look into JSONP.
In order to do cross-domain ajax calls you will either need to use a proxy or JSONP. Since you're setup for JSON already JSONP might be the easiest alternative. In short, JSONP entails wrapping your JSON data in a function call so it can be passed back to the calling script in a way that circumvents the Same Origin Policy.
In your case, you could wrap your json data with function named "myjsoncallback" so that it looks like this:
myjsoncallback({"h1": "cmPanel", "h2" : "cmAuto", "h3": 0})
And then change your ajax call to something like the following:
$.ajax({
url: 'http://www.foobar.com/array.json',
dataType: 'jsonp',
jsonpCallback: 'myjsoncallback', // Specify our callback function name
success: function(data) { console.log(data); }
});
Have you got access to the server from your web application? (same origin policy)
To use jsonp you could not simply add callback to the URL of the json file. The server should deliver a function that return the data. This file you could include with the default html script tag and execute the returned function afterwards.
To see the returned json you need to itterate the result
$.getJSON('array.json', function(data){
var items = [];
$.each(data, function(key, val) {
items.push('Key = ' + key + '<br/>Value = ' + val + '<br/><br/>');
});
alert(items.join(''));
});
array.json shoud be served with proper Content-Type:
text/javascript; charset=utf-8 if callback is used
application/json; charset=utf-8 if it is plain json
see here Best content type to serve JSONP?
to avoid problems from 'same origin policy'