Get data from a url when the extension is not .json - javascript

How would I display data from this json file when the extension is not .json? The other related questions i've found have involved files with .json as an extension and as a bit of a beginner to this I am struggling with it.
https://fantasy.premierleague.com/drf/elements/
Thanks.

Just treat it as if it was a JSON file except that there wont be a .json extension to your URL. So in pure JavaScript you can do this:
var request = new XMLHttpRequest();
var url = 'https://fantasy.premierleague.com/drf/elements/';
var jsonResponse;
httpRequest.onreadystatechange = parseJSON;
request.open('GET', url);
request.send();
function parseJSON() {
if (request.readyState() === XMLHttpRequest.done) {
if (request.status == 200) {
jsonResponse = JSON.parse(request.responseText);
} else {
console.log('An error occurred while processing the request.');
}
}
}

Related

How to load a json file with javascript locally without Jquery?

I'm creating a website to progress in javascript and I have a little problem, every ways I try, my browser doesn't want to load my json file.
I tried many codes i found on internet but none of them work (or I don't know how to make them work). Finally i fond this one which is quite easy to understand but yhis one too doesn't work and always return an error message.
function loadJSON(path,success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 1) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path , true);
xhr.send();
}
function test()
{
loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}
I run the test function but everytimes, the console return me an error. Someone have an idea to solve my problem ?
status is the HTTP response code.
200 means the request has been successful. The status will most likely never be 1.
Here is a list of HTTP codes
As a solution, I suggest using the fetch API, which is the modern way to query files.
Here are some examples on how to use it
If you really want to use AJAX, use this :
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Source : You Might Not Need jQuery

setting up tinymce with cloudinary in html and javascript

I've read the readme file at https://github.com/cloudinary/cloudinary_tinymce but still can't understand how to do it. Plus they do it on Ruby on Rails, which doesn't really help.
Do I really need to do server-side endpoint? It only asks for a signed URL. But I don't need it to be signed. How do I do it within JavaScript and HTML alone? I don't want to do anything inside my server except to render templates.
edit: I tried it with image_upload handler and it uploads to my Cloudinary account. But it won't give me the url for the image on successful upload (I expect to get something like https://res.cloudinary.com/strova/image/upload/v1527068409/asl_gjpmhn.jpg). Here's my code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'https://api.cloudinary.com/v1_1/strova/upload');
xhr.onload = function () {
var json;
if (xhr.status !== 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', cloudinary_upload_preset);
xhr.send(formData);
}
Try "faking" a POST request for one. I am still trying. To figure out why the documentation "requires" a POST request. The PHP example: https://www.tinymce.com/docs-3x//TinyMCE3x#Installation/ just echos back what gets POSTED to server. The plugin must be interpolated the posted content.
Inspired by your code, I was able to resolve this pain point for myself. The missing part was that after parsing the response, the secure_url from the response needed to be called and assigned to json in the format required by TinyMCE. Following is the code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
//restricted it to image only using resource_type = image in url, you can set it to auto for all types
xhr.open('POST', 'https://api.cloudinary.com/v1_1/<yourcloudname>/image/upload');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var url = response.secure_url; //get the url
var json = {location: url}; //set it in the format tinyMCE wants it
success(json.location);
}
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', '<YourUnsignedUploadPreset>');
xhr.send(formData);
}

How to get Blob from local image URL?

I have local image URL and I want to get the blob from it.
The only way I found was to do HTTP request 'get' on the local URL, and read the returned blob... but this is such a strange way.
The code snippet using HTTP:
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr=new XMLHttpRequest();
xhr.open('GET',results[i],true);
xhr.responseType='blob';
xhr.send();
xhr.onreadystatechange=function()
{
var blob;
if(xhr.readyState==4)
{
blob=readBody(xhr);
uploadPhoto(blob,storageRef);
}
};
Your image needs to be converted to base64 and then from base64 in to binary. This is done using .toDataURL() and dataURItoBlob()
It's pretty fiddly process, I've created a tutorial you can follow which walks you through the process.

Parsing JSON url in pure javascript

I'm trying to parse a url in pure javascript, just one executable file.
url = 'http://myurl.php?format=json'
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var mystuff = JSON.parse(request.responseText);
} else {
// some error
}
};
request.onerror = function() {
// some error
};
request.send();
console.log(mystuff);
When I do this, I get a XMLHttpRequest is not defined error. What's the best way to do this, the simplest way?
Thank you.
This statement is wrong you should url as a variable not "url" as a string,
request.open('GET', 'url', true);
to
request.open('GET', url, true);
Furthermore the xmlHttpRequest works only on some versions of browsers.
You could do something like this to check whether xmlhttpRequest works on your browser,
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}

Retrieve full path of a file using javascript

I would like to retrieve fullpath of a file and pass it to javascript. The requirement is that I need to retrieve XML file using JavaScript.
If it is a file you can access relatively to your web page do something like:
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
Assuming you have your web page next to the abc.xml...
This doesn't specify how to get full path to the XML - do youi still need it or loading it is enough?
For cross browser (from: http://developer.apple.com/internet/webcontent/xmlhttpreq.html)
var req;
loadXMLDoc("abc.xml");
function loadXMLDoc(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send("");
}
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
alert(req.responseXML);
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}
}
}
If you know the exact file up front, you can create a server-side program (i.e. service) to read the file, parse it and output it.
Then you'll just need to write some Javascript to make an AJAX call to this service (check out a Javascript library like Prototype or JQuery) to read the output of the service and thus the contents of the file.

Categories