I am trying to access a simple data file via javascript and finding it incredibly difficult. It will be placed on a remote server and hopefully could be accessed via http. I am new to javascript, but here goes: the best option so far I have found in JSONP, as stated here https://learn.jquery.com/ajax/working-with-jsonp/.
I have created an example datafile that I would have to process: http://murded.keeleleek.ee/test2.txt.
<html>
<head>
<title>My experiment</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
// Using YQL and JSONP
$.ajax({
url: "http://murded.keeleleek.ee/test2.txt",
// The name of the callback parameter, as specified by the YQL service
//jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell YQL what we want and that we want JSON
data: {
q: "dataprev",
format: "json"
},
// Work with the response
success: function(response) {
console.log(response); // server response
}
});
</script>
</html>
Eventually I would just like to use the JSON values as an array, and for now, just print them out to console or screen to make sure they are there. Is anyone able to help me troubleshoot this? Perhaps there is a much easier way?
Unfortunately I am new to both javascript and JSON, so there may be an easy newbie error there. The file should be on a remote server, and just read access should be enough for import. Many thanks!
A simple option is using $.getJson
$.getJSON(
"http://murded.keeleleek.ee/test2.txt",
data: {
q: "dataprev",
format: "json"
},
function( response ) {
console.log( response ); // server response
}
)
If your code, you said:
// Tell jQuery we're expecting JSONP
But your URL does not contain JSONP. It contains plain text.
In order to process it as JSONP you must format it as JSONP.
That means:
A core of JSON (See http://json.org/ for examples)
Wrapped with a JavaScript function call: foo(YOUR_JSON);
Served with an application/javascript content type (so you should use a .js file extension if you are serving up a static file)
If you are using a static file, then you are forced to hard code the callback name (foo in the example above). You need to tell jQuery what that callback name is instead of letting it generate one dynamically:
jsonp: "foo"
NB: JSONP is a hack to work around cross domain issues. It imposes quite a few limits compared to using XMLHttpRequest, including restrictions on what you can do to handle errors. There is now good support for CORS in browsers, so JSONP isn't needed any more. If you aren't making requests across origins then you don't event need that.
Related
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.
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.
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. :)
Is it possible to have a RSS feed by using a Javascript code?
It is totally possible.
If you want to use a local feed (on your own domain), you can simply use AJAX and parse that RSS feed.. This does not, however, work cross-site (as you might know), and unfortunately you cannot use this to get RSS feeds from other domains. (If you don't know AJAX, you can learn it at W3Schools or Tizag).
But Google has a solution. Using the Google AJAX Feed API, you can read RSS feeds from other domains without AJAX. You can read the docs for it to get a basic understanding of how it works.
An RSS feed is a type of xml file at a url. I'm not sure how you'd accomplish that with javascript (unless it's server side javascript). I think you need to do some homework on what you are trying to accomplish.
It's entirely possible. Create an Ajax request with JQuery.
$.ajax({
type: "GET",
url: "[your xml rss url]",
dataType: "xml",
success: function(x) {
$(x).find('foo').children().each(function(){
if(this.nodeName == "bar")
{
var x = $(this).attr("bar1");
var y = $(this).attr("bar2");
var z = $(this).attr("bar3");
return;
}
});
Jquery-Ajax
That depends what you mean. Probably not.
look at this jQuery plugin. It works great
http://www.zazar.net/developers/jquery/zrssfeed/
I'm trying to get a greasemonkey's script to work jquery and json.
this is the json url
http://www.sora101.net/auction.php?id=1&callback=
this is part of the script
$.getJSON("http://sora101.net/auction.php?id=1&callback=?",
function(data){
alert(data.id);
}
);
i always get something like this "Error: jsonp1282646809490 is not defined" in the console.
i also found this h**p://www.xucia.com/CrossSafe/test.html
on this site i get the right object returned but when i include this in my script it doesn't work...
can anyone help me? thanks and sorry for bad english
It seems like you should be using JSONP and now JSON as you're using different domains.
From jQyuery.getJSON() documentation:
Blockquote
JSONP If the URL includes the string
"callback=?" in the URL, the request
is treated as JSONP instead. See the
discussion of the jsonp data type in
$.ajax() for more details.