AJAX Cross Origin Error - ajax

I'm trying to set up my first AJAX dev site on MAMP. The image below shows my file structure inside a folder htdocs/javascriptAJAX/
The code in my app.js file is :
(function(){
var request = new XMLHttpRequest();
request.open('GET', '/data.txt');
request.onreadystatechange = function() {
if ((request.readyState===4) && (request.status===200)) {
console.log(request);
}
}
request.send();
})();
When i look in my console though, I'm getting the standard denial because of cross-origin requests:
XMLHttpRequest cannot load file:///data.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
How do I correct this? Surely if this is being run on MAMP it would have the same server?
Many thanks,
Emily

This problem was caused by the trailing forward slash in the .open() method.
Removing it solved the problem.

Related

Ajax in Phonegap not working

I know this question has been address many times on Stack Overflow, but none of the solutions are working for me.
I can't get ANY ajax requests to complete within my phonegap application when running on the device (Android 4.4.2), yet everything works fine from desktop browsers.
First I tried AngularJS $http
Then I tried jQuery .get
Then I tried raw xhr
In all cases, the request immediately fails with no response. I've tried requesting data from my own servers, and from google servers, and elsewhere, all the same. I've tried whitelisting my domains in config.xml, in many forms, still no effect. I've even opened the console, and manually created an XHR and tried to GET on it, and the same thing happens. The request immediately fails. If anyone can please help me out, that would be great. I'm on the latest version of pretty much all my software, having set up my dev environment just today.
Cross domain request headaches. The browser allows the cross domain request but phonegap on the device kills it. I've been there and it took some work getting used to dealing with it. Try using jquery and jsonp in an ajax get request.
Try adding <access origin="*" /> to your config.xml for testing.
Here's an example of an jquery ajax request taken from working code.
$.ajax({
timeout: 5000,
url: 'https://yourdomain.com/yourfile.php',
dataType: "jsonp",
jsonpCallback: 'yourcallbackfunction',
type: "GET",
crossDomain: true,
data: {'somedata':'your data string'},
error: function(xhrObj,text,errorObj){
if(xhrObj.status !== 200) {
var errorTxt='Error Log: ';
errorTxt=errorTxt+"Error code specific:'"+xhrObj.status+"'\n";
errorTxt=errorTxt+"Error status specific:'"+xhrObj.statusText+"'\n";
errorTxt=errorTxt+"Error code general:'"+text+"'\n";
errorTxt=errorTxt+"Error status general:'"+errorObj.message+"'\n";
console.log(errorTxt);
}
}
});
function yourcallbackfunction(data) {
// do cool stuff here
console.log(data);
}
Be sure to handle the headers on your servers response so that the response gets back to your client. Here's a sample processing function I used to return data. Sorry if php isn't your server side scripting language but hopefully you'll get the idea.
`function SendResults($data) {
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
header("content-type: application/json");
$callback = filter_input(INPUT_GET, 'callback', FILTER_SANITIZE_SPECIAL_CHARS);
echo "$callback(" . json_encode($data) . ")";
}`
Good luck.. Hope this helps you.

overcoming access-control-allow-origin in simple web map site

I am trying to set up a simple web page, that will draw a map with some openstreetmap data. I am serving the page for now with a (python) simpleHTTPserver on port 8000 of my local machine.
In my page I run a script that sends an AJAX request to openstreetmap.org:
$(document).ready(function() {
console.log ("Document is loaded.");
var map = L.mapbox.map('mapsection', 'examples.map-vyofok3q');
$.ajax({
url: "http://www.openstreetmap.org/api/0.6/way/252570871/full",
dataType: "xml",
success: function (xml) {
var layer = new L.OSM.DataLayer(xml).addTo(map);
map.fitBounds(layer.getBounds());
}
}); // end ajax
});
(The L. refers to Leaflet javascript libraries I included.) I am having trouble with same origin policy errors. Chrome says, "XMLHttpRequest cannot load http://www.openstreetmap.org/api/0.6/way/252570871/full. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
In serving the HTTP locally I followed the advice from a promising SO answer Can I set a header with python's SimpleHTTPServer? and so I ran $ python ajax-allower.py
where ajax-allower.py contains the code below. Can you explain why I still get the error, and suggest how I can get around it?
#!/usr/bin/env python
# runs the simple HTTP server while setting Access-Control-Allow-Origin
# so that AJAX requests can be made.
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Access-Control-Allow-Origin", "http://www.openstreetmap.org")
#self.send_header("Access-Control-Allow-Origin", "*")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
The ajax request fails because the object in question has been deleted.
If you try it with an object that still exists (e.g. http://www.openstreetmap.org/api/0.6/way/666/full), your jQuery code should perfectly work. Or if you grab the full history of the deleted object (http://www.openstreetmap.org/api/0.6/way/252570871/history), but that's probably not really what you want, I suppose.
It should be said, that the API probably should also send the CORS-headers for the failing (HTTP 410 Gone) requests, so that your client can detect the error code. This looks like a bug that should be reported on github.

nodejs Firefox vs Chrome (is it a bug)

Checking the simple code
var http = require('http');
var server = http.createServer(function(req, res){
console.log("Got Request");
res.end("");
});
When I am sending request to server using Firefox 8.0.1, I am geting console output once
Got Request
Using Chrome 16.0
Got Request
Got Request
why createServer is running 2 times on chrome??? is it a bug or something wrong with my code?
Browsers may submit addtional requests to the site, in which the most notable one is favicon.ico. Its purpose is to get the favicon for the site. And some plugins will also make additional requests. To make clear exactly what is being requested, you may print the url for the requests:
var http = require('http');
var server = http.createServer(function(req, res){
console.log(req.url); // <<<<<<<<<<<<<<<<<<<<<<<<<<<< print the requested url
res.end("");
});
server.listen(8000)

Fetching data through ajax using jQuery

I have two pages in different server.
Through ajax I would like to include some data: here is an example: link
The link is working through browser.
jQuery(window).ready(function() {
getPageWithAjax("http://www.betcatcher.com/index.php?page=valuebets&nr_row=6");
function getPageWithAjax(page)
{
//alert(page)
ajaxRequest = $.ajax(
{
url: page,
cache: false,
success: function(msg){ajaxResponse(msg)},
error: function(msg){ajaxResponse('Error loading data.'+msg.status)}
});
}
function ajaxResponse(msg)
{
$("#live_bet_ajax_content").html(msg);
}
});
But I'm getting error when I'm trying to get data.
I assume, that you call script from different domain. You should use JSONP which supports cross-domain calls. Read this article how to do this.
looks to me like a Same-Origin Policy problem. For new browsers you could enable Cross-Origin Resource Sharing (CORS) http://enable-cors.org/ for old browser you probably need to build a serverside proxy which rewrites the requests.

Why does this cross-domain request work in other browsers but not IE9?

I have some Ajax code that is working in Safari, Chrome and Firefox but not in IE9.
The page is on http://foo.com/test.aspx and it's making an AJAX request to a webservice hosted on https://service.foo.com. I thought I wouldn't have any cross-domain issues but given IE9 is blocking it, it appears that I do :(
var tempUrl = "https://service.foo.com/dummy.svc/test?hi=bye";
$.get(tempUrl, "html");
As I mentioned, the code works in the other 3 browsers, just not IE9. (I'm only concerned about IE9, not IE8 or older).
I did some digging and found this article on MSDN that says:
Cross-domain requests require mutual
consent between the Web page and the
server. You can initiate a
cross-domain request in your Web page
by creating an XDomainRequest object
off the window object and opening a
connection to a particular domain. The
browser will request data from the
domain's server by sending an Origin
header with the value of the origin.
It will only complete the connection
if the server responds with an
Access-Control-Allow-Origin header of
either * or the exact URL of the
requesting page. This behavior is part
of the World Wide Web Consortium
(W3C)'s Web Application Working
Group's draft framework on client-side
cross-domain communication that the
XDomainRequest object integrates with.
Before I go down the path of using XDR I wanted to verify with people smarter than me whether this is the right approach or not.
Add Response.AddHeader("Access-Control-Allow-Origin", "*"); to my page
Create condition jscript code that detects IE9 and uses XDR instead of the regular jquery call I'm using with $.get.
Am I totally off or is this the right way to go about this?
(Assuming it's the right way to go, where does the Acecss-Control-Allow-Origin response header go -- on my page at http://foo.com/test.aspx or on the webservice at https://service.foo.com?)
Instead of $.ajax(), use this custom code:
function newpostReq(url,callBack)
{
var xmlhttp;
if (window.XDomainRequest)
{
xmlhttp=new XDomainRequest();
xmlhttp.onload = function(){callBack(xmlhttp.responseText)};
}
else if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
callBack(xmlhttp.responseText);
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
Note: this works for GET requests.
To adapt it on POST requests change the following lines:
function newpostReq(url,callBack,data)
data is the URL encoded parameters of the post requests such as : key1=value1&key2=value%20two
xmlhttp.open("POST",url,true);
try{xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");}catch(e){}
xmlhttp.send(data);
To summarize, open the connection as POST request (Line 1), set the request header for urlencoded type of the post data (wrap it with try-catch for exceptional browsers) (Line 2), then send the data (Line 3).
i just wrestled with the same problem.
php backend, right mime and yes,
header('Access-Control-Allow-Origin: *');
worked in almost* every browser - except IE9.
seems like jQuery.getJSON doesn't automatically do XDR for ie9 - after creating a service proxy on the same domain, it worked.
* almost - opera acts up too.
edit: okay, opera did have the same problem as ie9. works like a charm now.
note: chrome, safari and the firefoxes (3.6-5) had no problem with the cross domain requests with ACAO:*.
what i don't understand is why a) microsoft uses a different object for cross domain requests and b) why jquery doesn't switch transparently (or at least provide an option to choose).
If this works in the other browsers (which support CORS), then your SVC seems to already be supporting this, but to be sure, use Fiddler2 to see what is going on.
The Access-Control-Allow-Origin header is used on the resource being requested, not on the page requesting it.

Resources