Pastebin.com Post - javascript

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.

Related

Native ajax call does not redirect on 302

I have been googling for hours now. I've read a dozen "answers" on Stackoverflow, all of them using jQuery.
This is the common answer...
The ajax-request will follow that redirect afaik
Well, it doesn't.
I am trying to send a PUT from a form via native JS AJAX
[Please I beg you, don't tell me to use jQuery. I found a bug in jQuery via PUT
(1) so I'm going around it]
This is my code snippet...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
This block works great, I can POST, PUT and DELETE without issues. The server receives the data and updates the DB according to the sent METHOD just fine.
My (SLIM based) PHP, upon successful completion, returns a 302 and a URL to go to.
This process works using POSTMAN hitting the PHP, and it goes to the right page.
Opening Chrome Tools/Network, it shows that the PHP is returning a 302 and than a 200
My response object contains the full HTML for a page in the responseText property.
Funny thing is, if I hard code a bad URL,the browser goes to my 404 page fine.
Your thoughts? (Please don't ask me or tell me to use jQuery)
EDIT/ADDENDUM -----------------------
I have discovered that the redirect is using the same METHOD of the original call.
I'm doing
PUT /user/1
the Redirect is doing
PUT http://myserver.test/
This is the right place to go. Now I understand the 405.
I don't have a PUT route defined, therefore the 405.
I create a PUT route and it works in POSTMAN but still gives me a 405 in Chrome and Firefox.
I have 2 issues to solve:
1) change the METHOD on the redirect
2) figure out why the browser doesn't like the 307
I found "a" solution. I'm not sure I like it, but...
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(data);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
window.location.replace(xhr.responseURL); // <---- solution
}
};

Ajax request with JavaScript responds with 302 (Found)

I am trying to send data by Ajax with the Post method, but the answer gives me 302 (Found) and I do not know what it can be. This is my code:
function sendData(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log("Response" + xmlhttp.responseText);
}
}
xmlhttp.open("POST", "request.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+document.getElementById('username').value);
}
and my .php file only print a message
<?php echo 'hello : ' . $_POST["name"] ?>
The 302 status code indicates that the resource you are requesting has redirected to another resource. If this is behind some authentication, or requiring a session to be active then yes, it would follow that the session timing out is responsible for the ajax resource being called to redirect to possibly a login screen maybe.
Try to use jQuery request, as it much simpler - also recommended in the above comments!
One way to get such a message is, to forget to add a / to the end of a URL, which is a "sub-directory" of the document root. As the URL your.domain/whatever and your.domain/whatever/ might not be the same. (Depending on server configuration, and the actual application serving those URLs.)
I can see, in this case you are actually POSTing to /request.php, so this might not apply, but just in case, I'd try to make that request 'by hand' and see what happens.
There are many browser plugins, that let you generate AJAX queries.

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.

What should a proper GET request and response look like in Node.js

I am working on a small project using Node.js.
The objective is to send an HTTP Request to an array of websites and display what they return to me.
First someone helped me to figure out that I needed a specific Node.js module (XMLHttpRequest). So I "required" it after installing it with NPM. Then I instantiate it.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
//I don't think I need this
xmlHttp.send(null);
//Log some stuff to the console, namely the "response"
console.log(xmlHttp.responseText);
console.log(xmlHttp.statusText);
console.log("Finished!");
Now I believe what this will do is send a GET message to "theUrl", and then save the response in the xmlHttp Object's responseText member.
So now I should have a response. I should be able to print that as text (console.log(xmlHttp.responseText);). What should be in this response?
I expect to get something like "200 OK" but that is nowhere in the response I get. Am I going about this in the right way?
I plan on using the Async Node.js module to send a request like this to an array of URLs, trim up their response (name of the website name, the response status code, and each of the response headers).
You can use below;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
// responseText => response body as string
// status => 200 is OK, 404 page not found
}
};
xhr.open("GET", "yor_url");
xhr.send();
responseText: response body as string
status: 200 is OK, 404 page not found

facebook graph api ajax XMLHttpRequest - Null result?

Summary: Keep getting null response despite public data and setting callback to enable cross domain JSON. Please help!
A similar question has been answered here
Using the new facebook graph api, ajax calls returns null (empty)
but I'm not using jquery and have tried to adapt my code to reflect that answer.
I'm trying to use a simple example to test a simple xmlhttprequest handler. I have this link in my page:
<a href='javascript:loadXMLDoc(\"https://graph.facebook.com/btaylor?callback=methodname\",\"\")'>AJAX LINK</a>
The callback=methodname parameter is to enable cross domain JSON
I'm using a generic XMLhttprequest builder:
var req; // Request object
function loadXMLDoc(url,params){
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
}
}
}
I then have a handler :
function processReqChange(){
if (req.readyState == 4) {
if (req.status == 200) {
alert("Done");
} else {
//alert("There was a problem retrieving the data:\n" + req.statusText);
alert("Status Code = "+req.status);
alert("There was a problem retrieving the data:\n");
alert("Failed : object = "+req);
alert(req.responseXML);
alert("Failed : response = "+req.responseText);
alert("Failed : status = "+req.statusText);
}
}else{
}
}
But I keep getting a null response (statusText OK, status code 0). Any ideas?
Thanks in advance
You can't make a cross-domain ajax request. Look into whether or not they support JSONP, or use the FB.api method from their javascript SDK
http://developers.facebook.com/docs/reference/javascript/FB.api
EDIT: I didn't read your post very thoroughly when I replied.
I see that you're adding the callback name to your ajax request, which isn't going to do any good because you're still making an XHR request, so it will still fail cross-domain. You seem to be misunderstanding how JSONP works.
Normally I'd just suggest using a framework like jQuery to abstract out the work that you shouldn't have to reinvent. If you're absolutely dedicated to doing this without jQuery, start by reading the wikipedia article on how JSONP works:
http://en.wikipedia.org/wiki/JSON#JSONP
The basic idea is:
Create a script node where the src attribute looks just like the URL you're trying to request now.
The server will respond with something like : methodname({"foo": "bar"}); instead of just JSON. Since this is being requested via a script node, your browser will execute the "methodname" function and pass in the results.
implement methodname(response) function to handle the response (i.e. do the work you intended to do in processReqChange)
Remove this line and try again:
req.setRequestHeader("Connection", "close");
It sets up the connection to close automatically, often before the send is complete.

Categories

Resources