XMLHttpRequest HTTP Headers - javascript

I'm trying to make a little script to rehost pictures on the web on imgur.
This is called Image Sideloading and you only need to point the browser to http://api.imgur.com/2/upload?url= + Picture's Url
It doesn't return any XML or JSON response so I can't parse it to get the img URL.
But I think I found a way to do this but can't get it to work properly. Here's the code I'm using.
$(document).ready(function() {
$("#button").click(function() {
str = $("input").val().toString();
link = "http://api.imgur.com/2/upload?url=" + str;
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.send();
var headers = xhr.getAllResponseHeaders().toLowerCase;
alert(headers);
});
});
And looking at Google Chrome's console these are the results generated after the script runs.
I am not allowed to post images yet so here's a link to the results: http://i.imgur.com/xCyIP.png
I need to somehow access that 4th response header because even though this method doesn't return any parsable XML or JSON response that link is the uploaded img's URL which is all I need.
So is there a way to access that info? Why is it cancelled?
Thanks everyone!

Well, the API must return something, else it is useless.
Actually, http://api.imgur.com/examples advises you to do something like:
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
var url = JSON.parse(xhr.responseText).upload.links.imgur_page;
alert(url);
}
xhr.send();
Edit. OK, I got it. Normally, the above code should work, but I think imgur is facing a problem. I will report the bug.
While the bug is still there, here is a dirty solution to serve your needs:
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
html = xhr.responseText;
alert(html.substr(html.indexOf('http://i.imgur.com/') + 19, 5));
}
xhr.send();
You code wasn't working because you weren't waiting for the answer. You have to catch it through a callback function.
Edit. The above code only works locally. As you're using jQuery, let me introduce the shortcut $.post:
$(document).ready(function() {
$("#button").click(function() {
$.post('http://api.imgur.com/2/upload.json', {
key: 'ec575de603b936e54c2b4a9f232d537e',
image: $("input").val().toString()
}, function(data) {
alert(data.upload.image.hash);
});
});
});​
http://jsfiddle.net/Le_Sphinx/rEfdS/

Related

How to get HTTP headers form data

I am using an external payment site to redirect to my own website. I need some of the form data in the headers and I cannot figure out how to grab the data. Here is a screenshot:
Inside the headers tab, I want to get the information from the Form Data tab.
The code below is what I was able to find regarding getting headers, but the problem is it only grabs the code from the ResponseHeaders tab. And req does not have any function to get the form data.
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
I want to see if there is a function where I can do something like
var formData = req.getFormData().toLowerCase();
There is no way, in browser-side JavaScript, to get information about the request that was used to get the current page from the server.
If you want access to it, you'll need to use server side code to dynamically generate the page and include it in the DOM (perhaps as a JavaScript object in a <script> element, or as a data-* attribute, or in <meta> elements) and then use JS to extract it from the DOM.
The mozilla site provides an example (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader)
var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(client.getResponseHeader("Content-Type"));
}
}
But fetch is nicer (see https://developer.mozilla.org/en-US/docs/Web/API/Response/headers):
fetch(myRequest).then(function(response) {
console.log(response.headers); // returns a Headers{} object
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});

chrome extension http request to website

I wanted to make a chrome extension that gets the html code from this website: https://free-proxy-list.net/
without actually going to that webpage.
I tried using the steps here:
https://developer.chrome.com/extensions/xhr
but the request kept showing as undefined when I tried to print it out.
The script I was using was:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', "url", true);
xhr.send(null);
document.write(xhr.send());
Note: not putting url in code since SO won't let me post a question with more than 2 links.
How would I get the code from this website in a string variable that I can parse?

JQuery: Check for HTTP status code and replace an image case specific [duplicate]

I developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.
Is there a way to programmatically determine if a link to a file is broken? If so, How?
Any guide or suggestion is appropriated.
If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET method, just HEAD and then check the HTTP status for the expect value (200, or just less than 400).
Here's a simple method provided from a related question:
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});
Issue is that JavaScript has the same origin policy so you can not grab content from another domain. This won't change by upvoting it (wondering about the 17 votes).
I think you need it for external links, so it is impossible just with .js ...
If the files are not on an external website, you could try making an ajax request for each file. If it comes back as a failure, then you know it doesn't exist, otherwise, if it completes and/or takes longer than a given threshold to return, you can guess that it exists. It's not always perfect, but generally 'filenotfound' requests are quick.
var threshold = 500,
successFunc = function(){ console.log('It exists!'); };
var myXHR = $.ajax({
url: $('#checkme').attr('href'),
type: 'text',
method: 'get',
error: function() {
console.log('file does not exist');
},
success: successFunc
});
setTimeout(function(){
myXHR.abort();
successFunc();
}, threshold);
You can $.ajax to it. If file does not exist you will get 404 error and then you can do whatever you need (UI-wise) in the error callback. It's up to you how to trigger the request (timer?) Of course if you also have ability to do some server-side coding you can do a single AJAX request - scan the directory and then return results as say JSON.
Like Sebastian says it is not possible due to the same origin policy. If the site can be published (temporarily) on a public domain you could use one of the link checker services out there. I am behind checkerr.org
As others have mentioned, because of JavaScript's same origin policy, simply using the function from the accepted answer does not work. A workaround to this is to use a proxy server. You don't have to use your own proxy for this, you can use this service for example: https://cors-escape.herokuapp.com (code here).
The code looks like this:
var proxyUrl = "https://cors-anywhere.herokuapp.com/";
function urlExists(url, callback) {
var sameOriginURL = proxyUrl + url;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', sameOriginURL);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
});

ajax javascript request not working in Safari

I have this snippet below to fetch how score count on shared links on Reddit. Using Google Chrome I get a JSON response I can work with, but in Safari the same code sends me directly to "onerror" instead.
Help please :)
UPDATE 1
For some reason it doesn't work for me but for everyone else. I have all plugins disabled but can only get it to work in incognito mode.
UPDATE 2
It seems it affect some people using Safari, but not all. Safe to say, the fault must be in the browser and not in my code :)
var myurl = 'http://www.google.com';
var jsonURL = 'http://www.reddit.com/api/info.json?url=' + myurl;
var request = new XMLHttpRequest();
request.open('GET', jsonURL, true);
request.onload = function () {
console.log('ON LOAD ------------------------------');
var response = JSON.parse(request.response);
console.log(response);
};
request.onerror = function () {
console.log('ON ERROR ------------------------------');
console.log(request);
};
request.send();

How get JSON data from external URL

I would like to be able to read information from a small page.
I have the address of a JSON service that displays the following information:
And I wish I could keep the number that appears.
I tested this example and work correctly, however when I try with my URL nothing happens. I do not know if I am to understand the problem correctly, but I wish someone could please help me.
If have any questions, I try to explain as best as possible.
I ask now apologize for the inconvenience.
The code that I used
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://MYADDRESS/json.do?_ULN[1]').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
You can't for security reasons. See the same origin policy for JavaScript.
There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.
The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
Your problem exist because of the browser Same-origin policy.
One solution to your problem is to use the method JSON-P or CORS. The method is well explained here : http://json-p.org/ and here : http://www.sitepoint.com/jsonp-examples/.

Categories