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.
Related
I am trying to retrieve a json feed every 1 second. The URL that I am trying to retrieve displays JSON in the browser but will not be retrieved via a jquery getJSON
http://www.ridestreamline.com/Services/JSONPRelay.svc/GetMapVehiclePoints
function getBusLoc() {
$.getJSON('http://www.ridestreamline.com/Services/JSONPRelay.svc/GetMapVehiclePoints?callback=?', function(data) {
console.log(data);
setTimeout(getBusLoc, 1000);
})
}
getBusLoc()
It has something to do with the above link. What am I missing? Fiddle here
This is because of same origin policy, you can't sent ajax request from host A to host B, you can use jsonp instead (if your service supports this) , or if you has control to server side and you don't mind to old browsers you can use x-access-control-allow-origin http header in response to OPTIONS request (more info here https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS)
There are a lot of answers all around the web how to prevent jQuery AJAX requests from being cached. This is not what I'm trying to do.
I need the AJAX request to be returned from the cache based on condition in my code. That is, when the request is issued during page load, it is completely ok to return cached response (in fact that is the intention). But when the user clicks a button, I need the same request to be refreshed from the server.
I know that I can do this by setting cache: false option in jQuery, but this will just request the data with a different URL thus not refreshing the response in the cache and during the next page load the request with cache: true will return the obsolete data.
I tried adding a Cache-Control header to the request but that does not have effect at least in IE10.
$.ajax({
url: Configuration.ApiRootUri + "Notifications",
type: "GET",
headers: { 'Cache-Control': refreshCache ? 'no-cache' : 'private' },
success: function(data) {}
});
Is it possible at all to force the browser to refresh a cached resource from script?
(note: rewritten after discussion in the comments)
A solution would be to store the response from the server in the localstorage and load it at page load if it does exists.
This avoid completely the request made to the server at start and act like a cache, but in the browser.
Here's a pseudo-algo example :
function loadRequest(){
Call Ajax request
On success, store the result in the localstorage, call updateHtml(result);
}
function updateHtml(data) {
Update the specific html (list, view, etc) with the data
}
$('#mybutton').on ('click', loadRequest);
$(function() {
Check if the data in the localstorage exists
if exists, call updateHtml(localstorage.value);
else call loadRequest
});
That's it!
Here's the issue. I'm extracting gmail contacts through an ajax call in javascript/jquery like this:
function getUserInfo() {
var xml_parse = "";
$.ajax({
url: SCOPE + '?max-results=9999&access_token=' + acToken
data: null,
success: function (resp) {
xml_parse = $.parseXML(resp);
callGmailHelperWebService(xml_parse);
},
dataType: "jsonp"
});
}
function callGmailHelperWebService(xml_parse) {
GmailHelperService.ConvertXMLToList(xml_parse, onSuccess, onFailed, null);
}
So, as you can see, if the initial ajax call is successful, i call a function which calls a web service that sits on the save server as my project (in fact, it's part of the project).
My web service (GmailHelperService) is wired up correctly, as I can definitely call it in other places (like right after this ajax call, for example). However, when I try to call it within the "success" portion of the ajax call, i get the following error:
Uncaught Error: SECURITY_ERR: DOM Exception 18
My theory is that this has something to do with cross-domain issues, but I can't understand why. And I certainly can't figure out how to fix this.
I'd appreciate any help.
JSONP is a data transfer method that involves sending your data in this format:
callback({"foo":"bar"});
As you can see, this is NOT xml. It is JSON wrapped in a callback method that will get executed when the request is done loading, thus allowing it to be cross-domain because it can be requested using a <script> tag.
You cannot simply change your dataType to JSONP and return xml, expecting it to work. XML != JSONP. You can however return XML in jsonp, for example, callback({"xml","... xml string here "}) but be mindful of quotes, all json keys and values must be wrapped in double quotes, inner-quotes need to be handled appropriately.
If your request is a same domain request (Same protocol, same subdomain, same domain, and same port,) then you can change your dataType to "XML" if you are returning XML. Otherwise, you need to either setup a proxy script to get the xml for you, or have your webservice return JSONP.
For example, the following urls are all considered cross-domain from each other.
http://example.com
http://www.example.com
https://example.com
https://www.example.com
http://example.com:8080
All of the above urls would be considered cross-domain, even if they are on the same server.
I have the following code:
$.get(url, {}, checkResponse)
And the following function:
function checkResponse(content) {}
The parameter "content" here is the result of the "get". I wanted to implement $.ajax to able to wait for the process to complete before it jump to the next chunk of code. I tried the following code but it didn't work.
$.ajax({
async: false,
type: 'GET',
url: url,
success: function (data) {
alert(data.toString());
checkResponse(data);
},
error: function (data) {
alert("error");
}
});
Here's what happened, the alert for the data.toString() gives empty string value while it should give me the url page content, and after it hits the alert it jumps to the error section and displays the alert "error".
According to the discussion in the comments section you are trying to send cross domain AJAX calls to arbitrary urls on the internet. Due to the same origin policy restriction that's built into the browsers this is not possible.
Possible workarounds involve using JSONP or CORS but since you will be sending requests to arbitrary urls that you have no control over they might not be an option. The only viable solution in this case is for you to write a server side script that you will host on your domain acting as a bridge. This script will receive an url as parameter and send an HTTP request to this url in order to retrieve the result. Then it will simply return the result back to the response. Finally you will send an AJAX request to your own server side script.
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