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

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. :)

Related

Opening a remote file with JSON data in javascript

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.

jQuery-media only fetches external content

I am using the jQuery media plugin to display HTML and PDF documents on my webpage. The plugin will load any externally hosted PDF/HTML with no issues. However, when I try to provide a URL to my application which returns the file content, it never attempts to fetch the URL.
I have tried a relative URL path (/ajax/...) and a full URL path (protocol, port & all) to the app view.
I have tested the URL I want the application to call by providing the URL to the browser and it properly returns the PDF document.
Anyone have an idea to force the plugin to fetch the URL I am providing?
So after rewriting the jquery.media plugin due to its complex nature, Greg and I found the solution. Effectively, the extension type must be specified in the url. For example the url '/mypdfs/my.pdf' would work but the url 'mypdfs/123' will not because jquery.media cannot determine the file type. A way to get around this is to make an ajax HEAD request and get the content type and then pass the appropriate extension type as an option to the media call.
$.ajax({
type: "HEAD",
async: true,
url: "http://myurl.com/file",
success: function(message, text, response){
var contentType = response.getResponseHeader('Content-Type');
// Map content types to extension type
$('.media').media({type: extensionType});
}
});
Also, Malsup's library seems to be unmaintained. We did a rewrite of the library which can currently be found here. We will be adding mapping Content-Type to file extensions as time permits so that this can be more flexibly implemented. Feel free to make a pull request.

How to access json content from external url

I'm new to jquery and javascript and I've been trying to access the contents of a json file from an external link with no luck. The json file is produced in the link below.
http://api.wmata.com/StationPrediction.svc/json/GetPrediction/A10,A11?api_key=hadtcpbh3w5xjbtyqrzgm88x
I noticed that several examples have a url similar to this "www.samplesite.com/testfile.json" However, as you can see above, the URL is not like this. Opening the link in Chrome takes you directly to the json file contents, however opening the file in IE asks you if you want to save the file "A10,A11.json".
All I want to do is be able to display the json file content in HTML. Can some please show me a brief example.
Thank you
$.ajax({
url: 'http://api.wmata.com/StationPrediction.svc/json/GetPrediction/A10,A11?api_key=hadtcpbh3w5xjbtyqrzgm88x',
dataType: 'jsonp',
success: function(data){// your code here
}
});
You can access the JSON only if the website having the JSON allows cross origin resource sharing(CORS). Find out if that is available, and if it is then post your code.
$.getJSON('http://api.wmata.com/StationPrediction.svc/json/GetPrediction/A10,A11?api_key=hadtcpbh3w5xjbtyqrzgm88x', function(data) {
//data is the JSON string
});
To retrieve JSON from servers outside your own domain, you should set up the callback to retrieve so called 'padded' JSON, which is easily done by adding the following to the jQuery .ajax() function:
dataType: 'jsonp'

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.

Load XML content in javascript application

I develop a javascript application which display data from xml with charts and lists.
For now I put some sample files onto the server's directory that I load with :
$.ajax({ type: 'GET', url: 'data/default.xml', dataType: 'xml', ...})
The Xml files can be very heavy so when one of them is loaded I put the data in an IndexedDB.
In a second time I would like to let the visitor loads its own xml file by giving the filepath of the xml (f.i. : /home/user/sample.xml). I do not want to upload this file onto the server because I do not need it and it could be too big. But I do want to load those data in the IndexedDB and let the app displays data without any call to the server.
I do not know if browsers could work this way?
If they could, how can I do such a trick?
You can't use Ajax to get data from a file on the client system, but in sufficiently modern browsers you can use the File API. MDN has a guide to the File API that is friendlier then the specification.

Categories

Resources