HTML/Javascript- get data from raw pastebin - javascript

I have a webpage in which I need to just get the raw data of a specified pastebin file, let's just say http://pastebin.com/qnNPx6G9, and store it as a variable. I've tried many, many, many variations on xml and ajax requests, but nothing works. Here's what I've tried. What am I doing wrong?
I've tried with Ajax:
$.ajax({
url: "http://pastebin.com/api/api_post.php",
type: "GET",
dataType: "x-www-form-urlencoded",
data: {
"api_dev_key": "mydevkey",
"api_option": "paste",
"api_paste_code": "blah blah"
},
success: function(res) {
alert(JSON.stringify(res));
},
error: function(res) {
alert(JSON.stringify(res));
}
});
//this is in the form of create paste, because I was seeing if it would work where get did not- it didn't.
And with regular XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST'/*also tried GET*/, 'http://pastebin.com/raw/qnNPx6G9', true); //I've also tried /raw.php?i=qnNPx6G9
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(this.responseText);
}
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("api_option=trends&api_dev_key=DEVKEY");
//I tried trends because creating a paste and getting a paste didn't work.
Please help! I'm sorry if this is a stupid question or anything is unclear, I'm not that good at understanding APIs. Thanks!
And no, I can't use PHP.

You are trying to make a CORS request that pastebin obviously doesn't allow as console shows up this error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
I think your only option is to use a server-side programming language in order to access pastebin remotely, CORS requests are only allowed just in the case the where remote server authorised it, else you have no way to bypass it.
Read more about CORS here

Related

Why does this email sending function not work?

Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.

XMLHttpRequest receiving undefined

I'm making a widget on iphone but I can't get data from the url.
On IE, I can get data. However, on chrome and on iphone I can't get the data but it only shows undefined instead of data.
function a() {
var url="www.xxx.xxx";
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
xmlDoc = request.responseXML;
}
please help me!! I'm really appreciated for any answers.
Create a function something like below,to receive the data from server.
request.onreadystatechange = function(){
if(request.readyState == 4){
console.log(request.responseText);
}
}
Please make sure that you are making request from the same Origin. That means if you are in site www.abc.com then you can make request for www.abc.com/download/ or www.abc.com/site and so on. But if you request for www.gdb.com then it will probably fail with this error in your console "No 'Access-Control-Allow-Origin' header is present on the requested resource." The browser prevents this activity for security reasons. It needs to be on the same domain.
Try using JQuery sometimes. It's API is very easy to use and is very helpful for doing tasks. You will need to add the script to the page first like this:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You can download the script or use the live version and link to it like above.
Next you can make a call like this to make a GET request. Observer that it returns data when successful. This makes your job easy but remember you need to make call from same domain.
$.ajax({
type: "GET",
url: "http://wwww.something.com"
})
.done(function( data ) {
alert(data);
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
To know more about Cross Site HTTP Requests: CORS
Here is a thread that may help you to understand better: “No 'Access-Control-Allow-Origin'
would setting the responseType work?
call the request.responseType = 'document'; before send.

How to make http authentication in REST API call from javascript

I need to call OpenMRS REST API from Java script to get data from OpenMRS. Below is my java script code:
function myfunction(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John", false);
xhr.setRequestHeader("Authorization: Basic YWRtaW46QWRtaW4xMjM");
xhr.send("");
alert(xhr.status);
}
Where YWRtaW46QWRtaW4xMjM is my base64 coded username:password as explained here. If I do not put the authorization line in the code and check the web app using Firebug, it returns 401 unauthorized status that is expected. But if I put the authorization, nothing is returned and in firebug I do not see any response as well. If I check the URL directly on browser, the page asks for username and password and after giving correct credential, it returns the data normaly. So I am getting some problem of providing the http authentication right from the java script of the app. I have also considered the methods explained here but no luck. Can anyone please help me to authorize the http request right from the javascript?
Here is another similar but different example of how to set the header for authorization purposes, but instead using JQuery and AJAX.
var token = "xyz"
var url = "http://localhost:8081/openmrs-standalone/ws/rest/v1/person?q=John"
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token)
},
})
.done(function (data) {
$.each(data, function (key, value) {
// Do Something
})
})
.fail(function (jqXHR, textStatus) {
alert("Error: " + textStatus);
})
Below is also an example of how you might get an access token using xhr instead of AJAX.
var data = "grant_type=password&username=myusername#website.com&password=MyPassword";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://somewebsite.net/token");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("client_id", "4444-4444-44de-4444");
xhr.send(data);
Beware of cross-site domain requests(if you're requesting a token that's not on localhost or within the domain that you are currently working in), as you'll need CORS for that. If you do run into a cross-domain issue, see this tutorial for help, and be sure you have enabled CORS requests from the API as well.

How to implement cross domain access in tomcat when using only jsp and javascript/ajax/jQuery and not using php?

I am developing a GIS Map Java web application using jsp, javascript/ajax/jQuery which is deployed in tomcat server. I need to implement cross-domain access here to get response from google api which return response in json format. But since cross domain access is not possible with xmlhttp, I cant get a response.
I have seen some posts suggesting the use of proxy.php in client side. But I am not using php and I would like to know if there is anyway to implement this using jsp/javascript alone. Is there any special configuration to be set in tomcat?? Kindly help.
Here is what i try to do:
var url = "http://maps.googleapis.com/maps/api/directions/json?origin=26.849307092121,75.781290279188&destination=26.932491611988,75.805420139913&alternatives=true&sensor=false";
xmlhttp.open("GET",url,false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send();
function AJAX_addShortestRoute() {
// if(xmlhttp.readyState == 4) {
var response=xmlhttp.responseText;
// document.write(response);
alert(response);
}`
But the request is never processed, since cross-domain access is not possible. Kindly help
Thanks and Regards
Ginger.
I resolved the issue. The only solution for cross domain (which I think) is use cross domain access through proxy server..
Here is how it is done.
var mapsUrl = 'http://maps.googleapis.com/maps/api/directions/json?origin='+source_y+','+source_x+'&destination='+dest_y+','+dest_x+'&alternatives=true&sensor=true';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl = 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodedUrl;
$.ajax({
url: proxyUrl,
dataType: 'jsonp',
cache: false,
success: function (result) {
//Your code goes here
}
});

Pastebin.com Post

I'm trying to post a new Pastebin through a popup window in Javascript. The issues I'm getting is it is saying "Bad API request, invalid api_option"
Link that I'm using:
http://pastebin.com/api/api_post.php?api_dev_key=<KEY>&api_paste_name=T‌​ITLE&api_option=paste&api_paste_code=SOMETEXT
It says to put api_option as paste. I've tried looking up other examples, but no luck yet. Has everyone ran into this problem?
Are you, by any chance, required to POST the data rather than GETting it?
Also, it might not be the best idea ever to put your API key on the internet like this.
How are you submitting this request to Pastebin? Is it via POST or GET? My best guess is that you're sending a GET request and the API requires a POST.
Try this:
let api = {
option: "paste",
user_key: "XXXXXXXXXXXX",
dev_key: 'XXXXXXXXXXXX',
paste_name: "MyTitle",
paste_format: "JSON",
paste_private: 0,
paste_code: ""
};
let request = new XMLHttpRequest();
request.open('POST', 'http://pastebin.com/api/api_post.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
data['test'] = 'Yeah PasteBin!';
dataString = 'api_option='+api.option+'&api_user_key='+api.user_key+'&api_dev_key='+api.dev_key+
'&api_paste_name='+api.paste_name+'&api_paste_format='+api.paste_format+
'&api_paste_private='+api.paste_private+'&api_paste_code='+data;
request.onreadystatechange = function() {
if (request.status == 200 && request.readyState == 4) {
alert("URL to new pastebin file: " + request.responseText);
}
}
request.send(dataString);
The main issue with your code is put everything in your request URL, what is fine if it is a GET request. The URL of PasteBin: api/api_post.php demands a POST request (notice the name?), so you have to send it in the body like I've shown you above.

Categories

Resources