ajax from same site as JS reference file? - ajax

I have a JS file running on my site, it works fine.
Now I want to put on another site with the full url of the script back to my site.
<script src="http://www-js.mydomains.com/some/path/file.js"></script>
now is it really still cross domain to an xml request on my server?
so in the file.js I have something like
dojo.xhrGet({url: '/some/path/file.xml', sync: true, handleAs: 'xml', error: function(result,args){alert(result.responseText+'-'+args.responseText)}, load: function(result){ ....
this just dies on other sites (great dojo response of undefined)... is there away around it

I think you should use "script" dojo/request/script instead of xhr.
require(["dojo/request/script", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/domReady!"],
function(script, dom, domConst, JSON, on){
on(dom.byId("startButton"), "click", function(){
domConst.place("<p>Requesting...</p>", "output");
script.get("helloworld.jsonp.js", {
jsonp: "callback"
}).then(function(data){
domConst.place("<p>response data: <code>" + JSON.stringify(data) + "</code></p>", "output");
});
});
});
http://dojotoolkit.org/reference-guide/1.9/dojo/request/script.html

now is it really still cross domain to an xml request on my server?
Yes. The origin is based on the URI of the HTML document hosting the script, not the URI the script was sourced from.
You should send the HTTP headers defined in the CORS specification to allow other sites to use your script (or their own scripts) to access content on your server.
Additionally, URIs accessed by JS are also relative to the document and not the script, so you will need to use an absolute or scheme relative URI instead of the server root relative URI you are presently using.

Related

Vue.js + Vue Resource No 'Access-Control-Allow-Origin'

Cross site ajax request with Vue.js 1.0 and Vue Resource. I get the following error: XMLHttpRequest cannot load http://dev.markitondemand.com/MODApis/Api/v2/Lookup/jsonp?input=NFLX&callback=handleResponse. No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have a basic understanding of the problem but not sure how to add a callback function with the request or if that is the best solution for this example. I put in the full request URL here just to make it easier to follow.
new Vue({
el: '#stockList',
data: function() {
return {
query: '',
stocks: []
};
},
ready: function() {
this.getStocks();
},
methods: {
getStocks: function() {
this.$http.get('http://dev.markitondemand.com/MODApis/Api/v2/Lookup/jsonp?input=NFLX&callback=handleResponse',
function(data) {
this.stocks = data;
}
);
}
}
})
I have almost zero understanding of networking, but I was able to get several remote apis to work using:
this.$http.jsonp
instead of
this.$http.get
"No Access-Control-Allow-Origin" header usually is a problem with the server. It means that the server is configured to only allow a person access to the API if the request comes from the same domain as the server. You either need to run the script from the website that you are requesting data from, or you need to change the server config to allow access to all domains.
If you don't have access to the server, and you don't want to run the script in the browser, then I think what you could do is use a headless browser like PhantomJS to navigate to the page, insert a script element into the dom that contains you script, execute the function and then return the data from the API. I could write the code out for you, but to be honest, it's a bit complex. You would have to know how to use node.js, and phantom.js. I've personally only used phantom.js for the Node 'html-pdf' package, but I'm sure with a little bit of reading you could figure out how to do it.
Set your local environment to http instead of https if you have no control over dev.markitondemand.com.

Absolute/relative address in ajax call in jquerymobile

The following code works fine in iPads and iPhone (4,5) in Safari and Chrome. In contrast, the ajax call won't work (runs straight to the onError function) in Android devices and desktop browsers.
When I exchange the absolute URL for a relative one, the success/failure outcomes are reversed in these two groups.
How do I get around this problem (I'm running jquerymobile 1.3.0 beta)? Thanks/Bruce
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#loginf").serialize();
$.ajax({
type: "POST",
url: "http://mydomain.org/m2/scripts/site/bpg_process.asp?id=lg",
cache: false,
data: formData,
dataType: 'json',
success: onSuccess,
error: onError
});
return false;
});
});
Do you know that cross-domain Ajax calls are not allowed ?
Your problem may be linked to the URL from which you're making the request, and not to the browser you're testing in.
Read this for more details : http://en.wikipedia.org/wiki/Same_origin_policy
The important thing here for you is that the policy excludes different subdomains.
Ex. if you're sending a request from http://www.mydomain.org to http://mydomain.org it will fail, and vice versa.
What i do in your case usually is use the complete URL "/m2/scripts/site/bpg_process.asp?id=lg" without the protocol and host but with the starting "/" so it can be referenced from anywhere in the URL tree.
What is the "relative URL" that you're using and that "doesn't work"?
Like darma has mentioned. "cross-domain Ajax calls are not allowed".
Use absolute "local" pathing instead.
a slash '/' at the beginning of a link referees to the document root.
if you need to refer to an external domain, use ajax to call a local .asp document that calls the external page for you and returns the data you want in json.
Im not sure what this is in asp but in php, curl works.

Cross Domain issue(Working in IE not in other browser)

I am fetching data from a URL using an AJAX call. It is giving a json object to me.
When I run the application, the page is working fine in IE with a conformation that
the page is accessing information that is not under its control.
This poses a security risk. Do you want to continue?
But that is not working in other browsers like Firefox, Chrome, Safari, etc.
i don't know what is the problem. Please explain to me why it is occurring and how to solve the issue?
My Code:
<!DOCTYPE html>
<html>
<head>
<title>Search Engine</title>
<script src="JS/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function () {
$.support.cors = true;
// create a script tag element
var script = document.createElement("script");
// set the attribute, using the URL to pass data via query parameters
script.setAttribute("src", "http://192.168.13.111:7090/?uname=bhagirathip&wt=json&fl=*,score");
script.setAttribute("type", "text/javascript");
// add the script tag to the document head, forcing an HTTP request
document.getElementsByTagName("head")[0].appendChild(script);
});
function Search() {
function callbackJsonHandler(data) {
alert(data); // This is the JSON data
}
}
</script>
</head>
<body>
<form id="form">
<div style="text-align: center">
<input type="search" id="searchInput" autofocus />
<input type="button" id="btnSearch" onclick="Search()" value="Search" />
</div>
</form>
</body>
</html>
You can't make cross-domain AJAX calls across domains. This is a security feature in web browsers to prevent malicious JavaScript code from scraping rendered data in a web page and then shipping it off to some rogue website on some other domain.
By restricting AJAX requests to same domain, browser vendors ensure that JavaScript imported from other sources cannot send data to any server other than the server the HTML page was served from.
In Internet Explorer, it's prompting you, but any smart user who encounters such a message is likely to say no. Presenting your users with such warning messages is not a good design practice and does not inspire confidence in the legitimacy of your application.
The only way that you can send data across domains is to use a browser hack technique called "script tag remoting", which essentially involves using HTML elements that aren't restricted by the same domain policy. For instance script tags can make HTTP GET requests to any server:
// create a script tag element
var script = document.createElement("script");
// set the attribute, using the URL to pass data via query parameters
script.setAttribute("src","http://192.168.9.11/userInput/?key="+userInput);
script.setAttribute("type","text/javascript");
// add the script tag to the document head, forcing an HTTP request
document.getElementsByTagName("head")[0].appendChild(script);
Using this method, you can send data to a remote server. Note that, to get JSON data back, you must wrap it, or pad it, in a JavaScript function and define a callback in the JavaScript code to handle the response:
function callbackJsonHandler(data) {
alert(data); // This is the JSON data
}
And your server-side code must return content text/javascript, calling the handler, and passing your JSON as an argument:
callbackJsonHandler({"key":"value","key1":"value2"});
When the browser downloads the JavaScript to the browser, the JavaScript runs immediately, giving you a hook to use to access the JSON in the response.
Since you're using jQuery, you can also check out jQuery JSONP, or JSON with Padding, which can be used to generate a JavaScript response so that you can handle callbacks from these requests to the remote server. Note that the server must be setup to handle JSONP requests for this to work properly, similar to the above setup.
Another solution to the issue of making cross-domain requests from a browser whose HTML document is served from exampleA.com to a server whose domain is exampleB.com is to use a proxy.
Let's assume that the HTML document you're working with is served from exampleA.com. You own exampleA.com, and you can access the server side and client side code. exampleB.com, on the other hand, is a remote server owned or controlled by someone else. exampleB.com has some data you want to use in exampleA.com.
We know that AJAX won't work, because of the same origin policy, which is in place to protect rogue apps from doing bad things with people's data. However, servers aren't restricted to same domain policy. This means that your app can do the following:
||exampleA.com/test.html|| ---> http req --> ||exampleA.com/getData|| --http req --> ||exampleB.com/getJSON||
Server-side: (As in your server, exampleA.com):
In other words, on your server that you're using to serve the HTML, you write some code that makes an HTTP request from your server to the third-party server:
// JSON URL which should be requested
$json_url = 'http://www.exampleB.com/getJSON';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
See Getting JSON Data with PHP Curl for more details. Each server-side platform has the ability to make HTTP connections to servers.
// now, send the data in the response
HttpResponse::status(200);
HttpResponse::setContentType('application/json');
HttpResponse::setData($result);
HttpResponse::send();
See PHP HTTPResponse. Again, whatever language you're working with should have the ability to return data from a string.
Put the above code in a file called "getJSON.php", assuming you're using PHP. Make sure there is no whitespace between the opening <?php and the beginning of the document; otherwise, you will not be able to set the headers. There is likely a better way to send this response, but since your platform isn't specified, I'll leave that as an exercise for the reader.
Client-side code:
var searchURL = "/getJSON.php"; //From this URL json formatted data is present.
$.ajax({
url: searchURL,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
try {
alert(data);
}
catch (err) {
alert(err);
}
}
});
Now, in the above JavaScript code, you make a same-domain AJAX request to your server exampleA.com, and then your server makes a request on your behalf to exampleB.com to get the data, then exampleA.com returns the data in the response to the browser.

Get remote xml file by AJAX and parse it with jquery

I'm developing a HTML5 application for Blackberry OS 5+.
I'm using jQuery to download and XML file and show it using this function:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://xxx.com/yyy/mTop",
dataType: "xml",
success: function(xml) {
$(xml).find('item').each(function(){
var tipo = $(this).find('tipo').text();
var porcentaje = $(this).find('porcentaje').text();
$('<div class="items"></div>').html('<p>' + tipo + ' - ' + porcentaje + '</p>').appendTo('#page-wrap');
});
}
});
});
But I'm getting this error:
XMLHttpRequest cannot load http://xxx.com/yyy/mTop. Origin file:// is not allowed by Access-Control-Allow-Origin.
How can I parse a remote XML file?
Maybe I need to convert XML retrieved to a DOM object for use with jQuery.
That's because of Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites
you should use JSONP instead.
And the reason why you dont have a file location in your link ( url: "http ://xxx.com/yyy/mTop" ) is becouse the site "produces" an xml the moment you visit the folder, slowing down the website each time you reach it..
What you must do is:
go to http ://xxx.com/yyy/mTop on your browser
right click - view source code - copy to notepad - save as .xml
upload file to another folder
then change your code url to this url: "http ://xxx.com/yyy/mTop/yourdailyXMLcopy. xml
and keep updating the file daily..else you will kill the server querying each time any user uses your thing for a huge job...
Part of your problem is your file path is to a folder and not an XML file. Start there and see if you're problem still exists.

Ajax requests ignore virtual application sub-folder name in URL for ASP.NET MVC application

My application is located on the server under a separate virtual directory. To access my ASP.NET MVC application users have to go to:
http://server-dev/superApp
I have a problem with Ajax/Json server requests ignoring the "superApp" directory part. Whenever an Ajax request is made Fiddler shows 404 because instead of http://server-dev/superApp/User/GetUsersJson for example, http://server-dev/User/GetUsersJson is called (note the missing superApp name).
Example of an Ajax request:
function GetUsers(id) {
$.ajax({
url: "/User/GetUsersJson/",
data:{ id: id},
datatype: 'json',
type:'post',
success: function (result) {
////Do stuff with returned result
}
});
}
Registered route:
r.Match("User/GetUsersJson", "User", "GetUsersJson");
Where should I look and what can I change to make sure that my application virtual folder is ALWAYS included in all URL requests ?
p.s. Please note that all Javascript/Ajax logic is kept in separate .js files so no RAZOR syntax is available.
Did you try using the HTML helper method ?
url: "#Url.ACtion("GetUsersJson","User)"
EDIT : As per the comment
You may get the Path name using the HTML Helper method and Keep that in a Global variable and access that in the external javascript file
In the view
<script type="text/javascript>
var globalGetJSONPath='#Url.ACtion("GetUsersJson","User)';
</script>
And now you can use it in the external file like this
$.ajax({
url: globalGetJSONPath,
data:{ id: id},
//remaining items....
});
I solved this stuff by passing variable to js that contains hostname+vdir. Because of heavy js url generation.
In other cases Shyju's answer is best way to solve this.
No way to do it without some server-side code generation. Easiest thing would be defining global variable (sorry) holding you application root and initializing it somewhere in master page.
Javascript generation of route urls always was one of the messiest parts of asp.net mvc.

Resources