jquery load html page as plain text - javascript

I'm trying to use jquery to load a local html page and display an alterated version of it.
I think I can do the alteration just fine, but I can't seem to load the page because it contains malformed tags such as unclosed IMG or BR tags, or </ characters,
which is normally ignored by web browsers
but when I'm using the $.get("mypage.html"); command,
firefox's javascript console shows an error telling me about the malformed tags and in the end, the ajax response only contains the page which send the ajax request (that's normal considering the loading failed)
I'm guessing the solution would be to load the html page as plain text so firefox won't catch a malformed tag error but I can't manage to force the response type and so, I always get the same error.
so far, I tried to set the ajax plugin like so :
$.ajax({
contentType: "text/plain; charset=utf-8",
dataType : "text",
success: function(data) {
alert(data);
}
});
contentType and dataType settings give me a responseText
but the load still fails so it contains the source code of the calling page
is there really no solution to this problem ? besides the obvious "manually correct the tags in the html pages"
I have to add that all of this is local, there won't be any server processing involved.
I'm using the latest firefox (20) and the jquery (1.9.1) updates to this day

XMLHttpRequest triggers an HTTP request; therefore, I'm pretty sure that you can't avoid an HTTP server being involved.

Related

XML request in jQuery gets ignored

I have build a webpage that focuses a lot on an XML file to populate it. Now I generated a second one for some additional tasks. Unfortunatly, everytime I try to parse it, it dows not succeed.
I am using very simple code to demonstrate the problem. I stripped the function, so everything it does is writing strings into the browser console.
Once I excecute this code, all I get is "pos1, pos3, pos4"
So the success function is not even excecuted. I know this sounds like a dumb question, but it is really hard for me, to find my mistake right now.
function insertFirstBeginnerQuestion(){
console.log('pos1');
$.ajax({
url: 'xml/questions.xml',
type: 'get',
dataType: 'xml',
success: function(data) {console.log('pos2');},
error: function(){console.log('pos3');},
});
console.log('pos4');
};
Are you trying it in server? Your code works for me and loads the xml properly. GET is a HTTP method, so you have to deploy this in a server and access using http protocol. Otherwise this will give you 404 error while trying to load the xml file.

Easiest way to load and read a local text file with javascript?

I have a .csv file that I wish to load that contains information that the .HTML page will format itself with. I'm not sure how to do this however,
Here's a simple image of the files: http://i.imgur.com/GHfrgff.png
I have looked into HTML5's FileReader and it seems like it will get the job done but it seems to require usage of input forms. I just want to load the file and be able to access the text inside and manipulate it as I see fit.
This post mentions AJAX, however the thing is that this webpage will only ever be deployed locally, so it's a bit iffy.
How is this usually done?
Since your web page and data file are in the same directory you can use AJAX to read the data file. However I note from the icons in your image that you are using Chrome. By default Chrome prevents just that feature and reports an access violation. To allow the data file to be read you must have invoked Chrome with a command line option --allow-file-access-from-files.
An alternative, which may work for you, is to use drag the file and drop into onto your web page. Refer to your preferred DOM reference for "drag and drop files".
You can totally make an ajax request to a local file, and get its content back.
If you are using jQuery, take a look at the $.get() function that will return the content of your file in a variable. You just to pass the path of your file in parameter, as you would do for querying a "normal" URL.
You cannot make cross domain ajax requests for security purposes. That's the whole point of having apis. However you can make an api out of the $.get request URL.
The solution is to use YQL (Yahoo Query Language) which is a pretty nifty tool for making api calls out of virtually any website. So then you can easily read the contents of the file and use it.
You might want to look at the official documentation and the YQL Console
I also wrote a blog post specifially for using YQL for cross domain ajax requests. Hope it helps
You can try AJAX (if you do not need asynchronous processing set "async" to false. This version below ran in any browser I tried when employed via a local web server (the address contains "localhost") and the text file was indeed in the UTF-8-format. If you want to start the page via the file system (the address starts with "file"), then Chrome (and likely Safari, too, but not Firefox) generates the "Origin null is not allowed by Access-Control-Allow-Origin."-error mentioned above. See the discussion here.
$.ajax({
async: false,
type: "GET",
url: "./testcsv.csv",
dataType: "text",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
//parse the file content here
}
});
The idea to use script-files which contain the settings as variables mentioned by Phrogz might be a viable option in your scenario, though. I was using files in the "Ini"-format to be changed by users.

Can't access another domain's valid json with jquery and ajax

I'm trying to access a JSON api of a certain adult-oriented website, but I can't get it to work. Here's the jsfiddle: http://jsfiddle.net/SSqwd/ and here is the code:
$.ajax({url: 'http://api.redtube.com/?data=redtube.Videos.searchVideos&search=sex&thumbsize=big&page=1&output=json&callback=?',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
I get
Uncaught SyntaxError: Unexpected token :
even though when I browse to the page myself and check the json on jsonlint, it is perfectly valid.
What's going wrong here?
Since you specified a cross domain request jQuery will by default attempt to request that URL using JSONP even though you've only set the dataType to JSON. So what actually happens is the following script tag is added to the DOM:
<script src="http://api.redtube.com/?data=redtube.Videos.searchVideos&search=sex&thumbsize=big&page=1&output=json&callback=?" type="text/javascript"></script>
(the ? actually gets replaced with a function name jQuery generates)
Your browser then tries to execute the returned data. However, as it is not actually JSONP and is just pure JSON what it returns is invalid javascript and hence you get the Syntax error.
You can reproduce the same error by just using:
<script src="http://api.redtube.com/?data=redtube.Videos.searchVideos&search=sex&thumbsize=big&page=1&output=json&callback=?" type="text/javascript"></script>
And doing nothing else. Or you can copy and paste the response from that URL and wrap it in script tags, you'll get the same error thrown.
The only way to solve this error is use an API that supports JSONP or implement a sort of proxy that requests the data via your own server on the same domain.

Browser Problems Parsing XML With JQuery

I need to access XML files with JQuery. I tried these two ways but I can't seem to contain them on one browser.
Here:
In Chrome, this works:
var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
alert(result);
Now I try to use it in conjunction with this code snippet, which works fine in IE:
jQuery.get('fruits.xml', function(data) {
alert(data);
});
The problem is, if I put both these codes together, one of them don't work on the other. So in Chrome I'd be able to access "Beethoven" while not being able to access "fruits.xml" but gives me this error:
XMLHttpRequest cannot load file:///C:/Python32/fruits.xml. Origin null is not allowed by Access-Control-Allow-Origin.
In IE on the other hand, I could access the whole content of fruits.xml and save it into a variable but the code for which I need to access XML attributes which works in Chrome doesn't work in IE.
As you can see, I want to get the contents of the xml using the 2nd snippet of code, while I will access the contents of the xml using the 1st snippet of code. Is there another way to access XML with Javascript? Can you help me with what's wrong with my codes?
Help?
The problem causing the error message is that you're sending an XHRRequest (The A in *A*JAX) to a file:// URL. For security reasons, this is being disabled by modern browsers. Instead, set up a webserver und it to access your page, via http://localhost/.. instead of file://C:/....
For the second part, make sure that you test loading fruits.xml first. Chances are there is an error in the XML stored in this file, or its structure is not what you expect. You can debug JavaScript in IE by pressing F12, going to the Scripting tab, and clicking Start Debugger. That way, you'll get a better error description than "doesn't work".
this may be a bug associated with chrome
loading local files in chrome bug/security feature
Problems with jQuery getJSON using local files in Chrome
Accessing relative URL's via "ajax" from "file://" content
as an advice dont wrap your xml in jquery and parse this way it may vary from browser to browser use instead .parseXML

parsing json file in javascript who's url extension is not .json

I want to parse json data from url which contain json data, but its extension is not .json
When I try to request response url using below code it make ajax request with 200 status code.
But I try with other url containing same data with .json extension, it works.
Here is my javascript code
var url='http://jsonurl.com/jsondata';
jQuery.ajax({
url: url,
dataType: 'json',
success: function(d){
jQuery.each(d,function(i){
console.log(i);
});
}
});
So I want solution to parse json content of file in javascript or in jquery, which dont have .json extension but contain json data .
CORRECTION: now seen your example url above and the content type is correct so that was a bit of a red herring.
The extension does not matter.
But the URL you are calling will need to return the correct content type which would be application/json Having said that our app uses text/javascript which works as I believe the browsers are a bit lenient.
So in my case I call a JSP getJSON.jsp that sets it's content type like this
<%# page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
I am guessing that when you use the .json extention the server is returning with the correct type but your other extensions will not.
I found the exact problem, after discussion with support team of API.
Actually the problem is with content type. They implemented some cache system for that json data, and when my script make request to API url, it send that json data and creates its cache and that cache remain active for some time. If my script create same request, then that json data served from cache who's content type is not json.
Now they are working on this issue.
BTW thanks Peter for help. :)

Categories

Resources