Import XML with jQuery: works on server, not locally - javascript

I'm working on a script that reads an XML file and then outputs the data. It works perfectly when it runs on my web server, but won't run from my local machine. (The "542Data.xml" file is stored in the same folder as the HTML page on both the server and my computer, and I checked that all file versions are the same. I've tried it in Firefox and Chrome with the same results.)
<div id="output"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "542Data.xml",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml)
{
$(xml).find("point").each(function(index)
{
$("#output").append("Name: " + $(this).attr("name") + "<br />");
});
}
</script>
The XML is structured as:
<?xml version="1.0"?>
<destinations>
<point name="Tot Lot at Bryan Park">
<lat>39.15611</lat>
<long>-86.52664</long>
<type>outdoors</type>
</point>
<point name="Playground at Cascades Park">
<lat>39.19633</lat>
<long>-86.53581</long>
<type>outdoors</type>
</point>
</destinations>
What do I need to change to get this working locally?
EDIT: I was wrong, it's working in Firefox. (embarrassed!)

Your script works fine for me in Firefox.
Chrome has some security feature that disallows what you wanted to do (using file:/// for AJAX requests). You need to start your browser with:
chrome --disable-web-security
to disable security checks. (--allow-file-access-from-files might also do the trick, but I haven't tested it yet)
Warning: disabling security checks affects your browser security and should only be used for temporary development purposes. If you plan to run the code from your local machine in a prolonged period of time, consider installing a web server on your local machine.

If by "working locally" you mean you have the html and xml file in a folder and open the HTML file by double clicking on it, then there is no way.
In order for it to work locally you need an web server which will resolve http requests. Opening a local file on a file system is not what is happening here. .ajax() is making a server request. Without a server it won't work.

What are you using to develop? Check if the development server you are using can serve XML files.

According to the given (small) info. There is may be a security reason i.e. importing jquery from google's repository. Please give more code or look at the error console in firefox - ctr+shift+j and copy paste the error if there is any, or just download jquery and include it with path in local location.

It is running on server but not on your machine. See, the ajax request needs a local server running. To make it work, start some local server on your machine. For example, if you're on Windows, then download WAMP, and if on Linux, then install LAMP. Put your files in www folder. Then start the local server..and then access your file using localhost/your_file_name. That'll give you the result as you want it.

Related

JavaScript googlemaps read coordinates from file

I want to display some markers using googlemaps. The information (coordinates) are stored in a local *.csv file (wich I want to use a "ressource-file").
How can I read this *.csv file? If I use "jQuery.get('myFile.csv', function (data) {..." it dosn't work.
The error message is: Cross origin requests are only supported for protocol schemes
Do I hava to make a file selection to read the file? Is there no other way?
Thanks
Is it possible that you are trying to load data from a file and not a running server(for example by double-clicking the .html from your file manager)?
If your are on the file:// protocol (which you can see in your url) this will not work. You could try changing to the development directory and runnig python3 -m http.server which will start a small development server. You can than change to http://localhost:8000 and see if it works.

Get HTML code of a local HTML file in Javascript

I'm developing a small application with HTML, CSS, Javascript, JQuery and JQTouch.
This is a LOCAL application. I've an index.html with some div's. When I click on a link in this file, I want to load HTML code of page1.html (same folder) and insert into a div of index.html the tag that I want of page1.html.
Example: Inject the content of (page1.html) into (index.html).
I try: http://api.jquery.com/load/
$('#loadContent').load('page1.html #test');
And the content of loadContent doesn't change. I include JQuery script into index.html...
I try http://api.jquery.com/html/ too, but I think it connect to the server.
Any idea? Thanks!
Make sure you're calling it after loadContent has been created. The following will run your load code when the document is ready to be written to.
$(function() {
$('#loadContent').load('page1.html #test');
});
Or you could run a local server. If you have python you can go to your directory with the files and run python -m SimpleHTTPServer for python 2.7 or python -m http.server for python 3.x
Most browsers will, by default, block this on a local file system as a security precaution. Have you tried it on a remote server?
I dont know much on jQuery. But still, you can do this, by loading the page1.html to a hidden iframe, then get the document.body.innerHTML of this page, and then append that node to the div you need. Its only HTML DOM in JavaScript.
But performance base, loading an iframe is always a costly one. This would do your job. However there may be many solutions in jQuery or other libraries, Sorry i don't know much on it.
It sounds like the problem is that the jQuery library isn't loading when you're running on localhost, or the AJAX request is failing for the same reason. This is due to protection built into the browser to prevent cross-site scripting.
See this "additional note" from the documentation for load:
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.
If you use any AJAX, you'll have to run this on a local web server. In which case you should just run this page from your local webserver rather than from the filesystem. Then you won't need any workarounds.
If you're on Windows, you could use UniServer.
If you aren't going to use any AJAX whatsoever (aren't using load), then you could write your code so that it falls back to a local version of jQuery if the remote version didn't load.
Here's an example of how, grabbed from this page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="/Scripts/lib/jquery/jquery-1.4.4.min.js"></script>'))</script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>!window.jQuery.validator && document.write('<script src="/Scripts/lib/jquery/jquery.validate.min.js"></script>')</script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
<script>!window.jQuery.validator.unobtrusive && document.write('<script src="/Scripts/lib/jquery/jquery.validate.unobtrusive.min.js"></script>')</script>

How to read contents of a file using javascript?

I have an input type="file" button. After I choose a file, I have to read the contents of the file using javascript. Is it possible to read/get contents of a chosen file using javascript or ajax?
You are all wrong in a way. It is possible. With the new File API you can read files before submitting them to the server. It is not available in all browsers yet though.
Check this example. Try to open a text file for example.
http://development.zeta-two.com/stable/file-api/file.html
Edit: Even though the question states "uploaded file" I interpret it as, "a file to be uploaded". Otherwise it doesn't make sense at all.
With AJAX its possible to read uploaded file but with pure javascript its not possible because javascript works on client side not on sever side.
if you are going to use jquery than Ajax call may be like this
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Reading files client side is hard:
How to read and write into file using JavaScript
Read a local file
Local file access with javascript
Unless you are trying to do it with local javascript:
Access Local Files with Local Javascript
Or server side javascript:
http://en.wikipedia.org/wiki/Server-side_JavaScript
Alternatively you can force your user to install an ActiveX object:
http://4umi.com/web/javascript/fileread.php
you cant do it using javascript directly. You can post the file to the server an then use ajax to retrieve the content.
Javascript is designed not to have access to the computer it is running on. This is so that rogue javascript can't read the user's harddrive.
You could look into using iframes though.
It is not possible to do it in java script. See Local file access with javascript
I agree with DoXicK above. You can post the file first on server and then you can use Ajax to read it.
That is not entirely impossible
A browser's usually runs Javascript(JavaScript Engine) in a sandboxed environment.
So you can use Windows Scripting Host or Internet Explorer in a trusted environment and use the FileSystemObject
or use
Or upload a file to your server and use the XMLHttpRequest object.(in other words - Ajax)
For IE use the FileSystemObject (which is found on all Windows systems).
For Firefox:
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");
See https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO
To see these methods and others in use, look at TiddlyWiki app to see how it does it across all major browsers.

Xml to js code problem

So i'm very new to xml to javascript so i thought I would learn from w3schools, but this site
http://www.w3schools.com/xml/xml_to_html.asp shows an example that I can't mimic locally. I copy/pasted the .js and downloaded the xml but I just get a blank screen!
It's working in there try it yourself but not for me? Do I need it on a server or something?
Yes, that code retrieves the XML data from a web server using AJAX. Since you don't have a server running locally, you can change the URL to point directly to the w3school's version:
xmlhttp.open("GET","http://www.w3schools.com/xml/cd_catalog.xml",false);
Alternatively, play around on their online version ;)
well i guess you have to add the example xml (cd_catalog.xml) to your file system. and you definitively have to access the html file on a server (apache i.e.)
First, ensure that both HTML file (with the Javascript block in it) and XML file are placed in the same directory.
Next, you probably need to place those files under your local web-server and open the HTML like this:
http://[local server host]/ajax.html
instead of opening the file directly from e.g. Windows Explorer:
C:\[path to the file]\ajax.html
For the latter case you'll get an "Access is denied" error.
-- Pavel
Are you running this under a web server or just creating a couple of text files and loading them in your browser?
The "GET" request this relies upon could possibly be failing.
Use Apache or another similar HTTP server and run the example as if it were hosted on the web.

External JSON data with offline development

I am developing a web app that accesses some external JSON data. I'm currently using jQuery's getJSON to get the data and call the callback.
My internet at home is terrible, so I'm regularly not connected. I am looking for a way to develop this app while disconnected from the internet.
My initial thought was to have an OFFLINE variable that I set, which changes the location of the scripts to a local file, but because jQuery's getJSON uses dynamically named functions for callbacks, it would need some server intelligence.
More info on how getJSON callbacks work here: http://docs.jquery.com/Ajax/jQuery.getJSON
I'm sure there's an easier way. Any suggestions?
** Edit **
Let me try and clarify a bit
I'm currently running a local web server. I have to - script tags can't reference a local file, for security reasons.
I'm currently calling getJSON with the url: http://twitter.com/status/user_timeline/user.json?callback=?
If I downloaded that json response and hosted it on the local webserver, it wouldn't work, because the callback name will change every time, yet the feed will have the function name it was originally fetched with.
I have a similar problem. Try xampp for an easy php/apache/mysql install on your machine.
I use dreamhost to host my site. I manage everything with a subversion repository, which allows me to simply do 'svn update' on my live site when I am ready to pull in my changes.
I also define all my paths relative to a base_url variable, which is set depending on the http host, so I don't have to change anything for my site to run on different webservers. I use codeigniter, and my config file looks like this:
switch($_SERVER['HTTP_HOST']) {
case "claytonhp":
$config['base_url'] = "http://claytonhp/<project_url>";
break;
// etc.
}
To use that same path in my javascript, I put the following at the top of each html file:
<script type="text/javascript">
siteUrl = '<?= base_url();?>';
</script>
<script type="text/javascript" src="<?= base_url();?>public/scripts/external/jquery/jquery.js"></script>
<!-- Local functionality -->
<script type="text/javascript" src="<?= base_url();?>public/scripts/common.js"></script>
<!-- etc -->
Then, my jquery ajax calls look like this:
$.ajax({
type: "POST",
url: siteUrl + "index.php/ajax_controller/getSomeData",
dataType: "json",
data: "id=5",
success: successCallback,
error: errorCallback
});
Just use a web server (IIS is built into Windows, or use Apache, or XAMP otherwise). That way, you're always connected to your web site (use http://localhost/...).
Quick solution is to just run a local web server. This is a good idea for all sorts of reasons.
If you don't want to do that, just define the URL to get the JSON from somewhere global, and pass it to getJSON(). Just don't forget to set it back before you put your code up on the server.
I used a local sinatra webserver, and replaced the hosts in my /etc/hosts file. It's nice because it's super easy to define new services.
I often forget to reset my hosts file, which can cause a lot of frustration, so I created a script to wrap the whole thing as well.
Here's an example that will serve up a twitter user feed.
run.sh
#!/bin/bash
cp /etc/hosts /etc/hosts.original
cat offline_hosts >> /etc/hosts
ruby server.rb -p 80
cp /etc/hosts.original /etc/hosts
offline_hosts
127.0.0.1 twitter.com
server.rb
#!/usr/bin/ruby
require 'sinatra'
# twitter user
# http://twitter.com/status/user_timeline/$USER.json&callback=?
get '/status/user_timeline/:username.json', :host_name => /twitter\.com/ do
render_file "feeds/#{params[:username]}.json"
end
def render_file filename
output = File.open(filename).read
output = "#{params[:callback]}(#{output});" if params[:callback]
output
end

Categories

Resources