I am working on a project in which I'm in need to get the data stored in XML file using javascript or jQuery. My Script code is
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST", //I also tried POST method
url: "match.xml",
dataType: "xml",
success: function(data){
$(data).find("mchdata match").each(function(){ //match is a tag
$(".container").append('<div class="head">'+ $(this).attr("src") +'</div>'); //src is an attribute of match tag.
});
},
error: function(){
$(".container").text("Error occured");
}
});
});
</script>
Html code is
<body>
<div class="container"></div>
</body>
Every time I run this code it's showing 'Error occurred' message in container div. I tried to inspect the page, it shows an error message like
Failed to load file:///C:/Users/vinay%20Dahiya/Desktop/match.xml:
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https.
I don't know what does it mean. Is this the right script url 'm using
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
I'm trying to solve this for last 2-3 days but don't know what actually wrong in the code
XML file is View XML file
Thanks in advance.
I'm suggesting a quick fix for this, since you are testing this on a local machine and nowhere near production,
go to the folder where the xml is and start a simple python server there.
use
python -m SimpleHTTPServer
then you can access your file using,
http://localhost:8000/xxyy.xml
Related
Trying to do a simple AJAX call (teaching myself). I have a .txt file in same folder as html. What am I doing wrong here? Thanks.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#poo").submit(function(e){
e.preventDefault(); //stop submit
$.ajax({
type: "GET",
url: "data.txt",
data: "",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
}
});
});
});
</script>
</head>
<body>
<form id="poo">
<input type="text"> </input>
<input type="submit"> </input>
</form>
<br>
<br>
<div style='display: none;'>
<p id="foo">this shows</p>
</div>
Start Over
</body>
</head>
</html>
This is a convenience function that loads remote files via AJAX and uses .innerHTML() to load it into any elements in your jQuery selector.
// Does the exact same thing as the entire block of code you wrote..
// These jQuery methods are chainable so you can do this in 1 statement.
$("#foo") // Contains the DOM reference,
// so no need to use getElementById().
.load("data.txt") // Loads "data.txt" into "#foo".
.show(); // Makes "#foo" visible.
Relevant:
jQuery selectors and method chaining
jQuery load() method
jQuery show() method.
Per your comments, you had some other issues.
You said you weren't sure if jQuery was loaded. jQuery is just javascript, so you include it in <script></script> tags. The easiest way is to use jQuery's CDN. Click on the link, then choose the version and format you want. There will be a pop-up containing the script tag, just copy it into the page, preferably before any other Javascript you have on the page. If you're not sure which version/format to use, v1.x, minified is the way to go.
You mentioned that you were running it locally. The problem is, Javascript isn't supposed to have direct access to your filesystem. It will attempt to request the file over the http protocol, without having server software you can only request files over the file:// protocol.
There are zillions of topics on this all over the internet, but to solve it you should install a server. XAMPP is a good one and it's cross platform. Download that and your application will work in all your browsers. It will work in your browsers when you upload it to a server as well
try to add the dataType: "text"
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
})
I am converting my webapp from PHP / HTML to JS/HTML so that it can work with phonegap. I am keeping the php server side files separate and on the server. I am having issues with executing AJAX calls from my local HTML file. When i check the console on chrome, it doesn't show any errors, but the ajax call doesn't return any value either. Ive simplified the issue so that people can easily understand what the problem is.
My JS code is
<head>
</head>
<body>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$.ajax({
url: "http://www.betsmart.org/betsmart/models/test.php",
method: "get",
dataType: "json",
crossDomain: true,
success: function(result){
console.log(result);
$("#text").html(result);
}
});
</script>
<h1 id="text"></h1>
</body>
My PHP code in test.php is
<?php
header("Access-Control-Allow-Origin: *");
echo "test";
?>
The success callback isn't executing. I understand the same origin policy will probably come into play here but i thought that doesn't matter with Phonegap.
Please do let me know where i'm going wrong or an alternate way to do this. If i have to use jsonp, what will be the client side and server side code?
Thanks
Gagan
I mentioned i read the suggested link ...and Could not able to understand the
suggestion .."Use Greasemonkey to modify Pages and start writing some
javascript to modify a web page
I am loading a text file with $.ajax. When running the code on Firefox, I get the following error:
Error: ["Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "<unknown>"]
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("button").click(function () {
$.ajax({ url: "demo_test.txt",
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
cache:false
});
return false;
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
I've already read the following questions:
firefox reading web page from local JS file -- access to restricted URI denied, code: 1012, nsresult: NS_ERROR_DOM_BAD_URI
Error: [Exception... "Access to restricted URI denied" .... while calling $.ajax method
It was suggested that file system should not be used, so changed the URL to http://demo_test.txt, but that did not solve the issue.
I also heard that it might be because of a cross domain issue. If so, what exactly is meant by that, and how should I solve the problem?
Browser security prevents the code from running. You are better off running a local server such as IIS or Apache.
You can change your browser to run local content by changing a browser config
Firefox
Go to about:config
Find security.fileuri.strict_origin_policy parameter
Set it to false
I finally seems to Get it working . Here is working Script
$("button").click(function(){
$.ajax({url:"http://localhost/demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
Workaround : put the html file and text file on local server (IIS) New Site .
Using JavaScript, I want to retrieve the content of the script files. These script files remain in local(in web page).
For example.
In web page, there is a script,
<script src="tool.js"></script>
Latter, I want to get the content of tool.js and process the retrieved result (like dump its content).
I have tried to use jQuery.getScript. However, it tells me that Origin null is not allowed by Access-Control-Allow-Origin.
try an ajax like the following
$.ajax('/tool.js', {
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function() {
console.log("call failed");
}
});
You need to configure your Access-Control-Allow-Origin:
Access-Control-Allow-Origin: *
This lets you use any resource to obtain assets from an external domain. Do this first and either Mahan's or Lars's solution will work.
More info:
Access-Control-Allow-Origin Multiple Origin Domains?
try using jquery.load() and put its contents on an element and use .html()
<html>
</head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
//setup ajax to work locally
$.ajaxSetup({
crossDomain: false,
isLocal :true
});
$("#a").load('jquery.js', function() {
alert($("#a").html());
});
});
</script>
</head>
<body>
<span id="a" style="display:none;"></span>
</body>
</html>
Browser Check:
the code above works and tested in FF, Safari, Opera and IE
but if you keep on having problem with Origin null is not allowed by Access-Control-Allow-Origin then having a web server installed is needed as said here; Origin null is not allowed by Access-Control-Allow-Origin
Reference:
http://api.jquery.com/load/
code for your disposal : http://jsfiddle.net/PeaH3/1/
EDIT: I have discovered that this is a 405 error. So there is something going on with the webserver and handling POST methods.
I am having a strange occurrence. I have identical javascript code on both my test environment and production environment.
The test environment functions, and the production does not. Here is my identical code.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>
<script type="text/javascript" src="./js/jquery.scrollTo-min.js"></script>
</head>
<body>
<div class="content" id="content">
<a id="changeText" href="test.html">Change</a>
</div>
<script>
$(document).ready(function() {
$("#changeText").live('click', function(){
var url = $(this).attr("href");
$("#content").load(url, {var1:Math.random()*99999},function(){
alert(url + " loaded");
});
$.scrollTo("0%", 400);
return false;
});
});
</script>
</body>
</html>
Both environments report that
alert(url + " loaded");
is happening. But only my test environment actually displays the change.
The production webserver has "test.html" available in the correct location.
Are you sure the scrollTo script is being included on the production server ( or am I misinterpreting what you mean by change ) ? Perhaps try a root relative path instead of './js'? I would check Firebug's script tab to ensure it is being included.
405 errors mean that the URL you're sending to isn't expecting you to send the data in that manner. For example, if you're sending a POST request to a URL that's only designed to handle a GET request, you'll get this error.
My guess is whatever server you're running on is set up to not allow POST data to be sent to a page with a .html extension, causing the error you're seeing. Try changing the extension to a .php, .aspx, etc, and see if that helps.