Imgur API return "undefined" - javascript

I've the following js code to upload image to imgur using Auth.
<script type="text/javascript">
window.ondragover = function(e) {e.preventDefault()}
window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files[0]); }
function upload(file) {
if (!file || !file.type.match(/image.*/)) return;
document.body.className = "uploading";
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.imgur.com/3/image.json");
xhr.onload = function() {
var code = '[img]' + JSON.parse(xhr.responseText).data.link + '[/img]';
var editor = eval('opener.' + 'clickableEditor');
editor.performInsert(code);
javascript:window.close()
}
xhr.setRequestHeader('Authorization', '39-letter-client-secret-code');
xhr.send(fd);
}
</script>
It doesn't uploads image to the imgur, but it returns data "undefined". Can you please mention me if I'm missing something here?

I've seen an issue in this line;
xhr.setRequestHeader('Authorization', '39-letter-client-secret-code');
I've changed it to;
xhr.setRequestHeader('Authorization', 'Client-ID 15-letter-Client-ID');
and it works. Sorry to bother you.

Related

Ajax jquery POST implementation in vanilla javascript [duplicate]

I'd like to send some data using an XMLHttpRequest in JavaScript.
Say I have the following form in HTML:
<form name="inputform" action="somewhere" method="post">
<input type="hidden" value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input type="hidden" value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
How can I write the equivalent using an XMLHttpRequest in JavaScript?
The code below demonstrates on how to do this.
var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
In case you have/create an object you can turn it into params using the following code, i.e:
var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;
// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
Or if you can count on browser support you could use FormData:
var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
Use modern JavaScript!
I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.
const url = "http://example.com";
fetch(url, {
method : "POST",
body: new FormData(document.getElementById("inputform")),
// -- or --
// body : JSON.stringify({
// user : document.getElementById('user').value,
// ...
// })
}).then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
In Node.js, you'll need to import fetch using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url, optionalOptions)
.then(response => response.json()) // .text(), etc.
.catch((e) => {});
More Info:
Mozilla Documentation
Can I Use (96% Nov 2020)
David Walsh Tutorial
Here is a complete solution with application-json:
// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">
// return stops normal action and runs login()
<button onclick="return login()">Submit</button>
<script>
function login() {
// Form fields, see IDs above
const params = {
email: document.querySelector('#loginEmail').value,
password: document.querySelector('#loginPassword').value
}
const http = new XMLHttpRequest()
http.open('POST', '/login')
http.setRequestHeader('Content-type', 'application/json')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
// Do whatever with response
alert(http.responseText)
}
}
</script>
Ensure that your Backend API can parse JSON.
For example, in Express JS:
import bodyParser from 'body-parser'
app.use(bodyParser.json())
Minimal use of FormData to submit an AJAX request
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert (xhr.responseText); } // success case
xhr.onerror = function(){ alert (xhr.responseText); } // failure case
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData (oFormElement));
return false;
}
</script>
</head>
<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
<input type="hidden" value="person" name="user" />
<input type="hidden" value="password" name="pwd" />
<input type="hidden" value="place" name="organization" />
<input type="hidden" value="key" name="requiredkey" />
<input type="submit" value="post request"/>
</form>
</body>
</html>
Remarks
This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.
This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.
Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.
NO PLUGINS NEEDED!
Select the below code and drag that into in BOOKMARK BAR (if you don't see it, enable from Browser Settings), then EDIT that link :
javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);
That's all! Now you can visit any website, and click that button in BOOKMARK BAR!
NOTE:
The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:
javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) { var xForm= document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank"); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } document.body.appendChild(xForm); xForm.submit(); } parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0);
I have faced similar problem, using the same post and and this link I have resolved my issue.
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This link has completed information.
Try to use json object instead of formdata. below is the code working for me. formdata doesnot work for me either, hence I came up with this solution.
var jdata = new Object();
jdata.level = levelVal; // level is key and levelVal is value
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://MyURL", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(jdata));
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate
http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');
I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
If you're using JSON and not URL-encoded data, pass application/json instead
var util = {
getAttribute: function (dom, attr) {
if (dom.getAttribute !== undefined) {
return dom.getAttribute(attr);
} else if (dom[attr] !== undefined) {
return dom[attr];
} else {
return null;
}
},
addEvent: function (obj, evtName, func) {
//Primero revisar attributos si existe o no.
if (obj.addEventListener) {
obj.addEventListener(evtName, func, false);
} else if (obj.attachEvent) {
obj.attachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = func;
} else {
obj[evtName] = func;
}
}
},
removeEvent: function (obj, evtName, func) {
if (obj.removeEventListener) {
obj.removeEventListener(evtName, func, false);
} else if (obj.detachEvent) {
obj.detachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = null;
} else {
obj[evtName] = null;
}
}
},
getAjaxObject: function () {
var xhttp = null;
//XDomainRequest
if ("XMLHttpRequest" in window) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhttp;
}
};
//START CODE HERE.
var xhr = util.getAjaxObject();
var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
if (isUpload) {
util.addEvent(xhr, "progress", xhrEvt.onProgress());
util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
util.addEvent(xhr, "abort", xhrEvt.onAbort);
}
util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);
var xhrEvt = {
onProgress: function (e) {
if (e.lengthComputable) {
//Loaded bytes.
var cLoaded = e.loaded;
}
},
onLoadStart: function () {
},
onAbort: function () {
},
onReadyState: function () {
var state = xhr.readyState;
var httpStatus = xhr.status;
if (state === 4 && httpStatus === 200) {
//Completed success.
var data = xhr.responseText;
}
}
};
//CONTINUE YOUR CODE HERE.
xhr.open('POST', 'mypage.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if ('FormData' in window) {
var formData = new FormData();
formData.append("user", "aaaaa");
formData.append("pass", "bbbbb");
xhr.send(formData);
} else {
xhr.send("?user=aaaaa&pass=bbbbb");
}
This helped me as I wanted to use only xmlHttpRequest and post an object as form data:
function sendData(data) {
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for(name in data) {
FD.append(name, data[name]);
}
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
Short & modern
You can catch form input values using FormData and send them by fetch
fetch(form.action, {method:'post', body: new FormData(form)});
function send() {
let form = document.forms['inputform'];
fetch(form.action, {method:'post', body: new FormData(form)});
}
<form name="inputform" action="somewhere" method="post">
<input value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
<!-- I remove type="hidden" for some inputs above only for show them --><br>
Look: chrome console>network and click <button onclick="send()">send</button>
Just for feature readers finding this question. I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE. Here is what I came up with:
function post(path, data, callback) {
"use strict";
var request = new XMLHttpRequest();
if (path === "") {
path = "/";
}
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function (d) {
callback(d.currentTarget.response);
};
request.send(serialize(data));
}
You can you it like so:
post("", {orem: ipsum, name: binny}, function (response) {
console.log(respone);
})

Why are my javascript functions are stacking?

I am making a messaging system and I have recently implemented a file uploader, and my javascript functions aren't working, if I press the input file button then press cancel, the next time I upload a file it does it 3 times. It's as if since I don't upload anything, they just sit there and then the function stack. Here is my input :
<input type="file" id="file" onclick="bro()"name="file" value="FILE UPLOAD" style="opacity: 0;z-index: 100000; bottom: 17.5px; position: fixed; right: 10px;">
And here is my javascript function
function bro() {
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
};
The problem is, I can't just put the function because I use an ajax request thing to display the input. To explain more since I am making a messaging system I have a sidebar with group id and group name. I use this function :
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxLoad(page, id, id2){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('mainpage');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?id=" + id + "&id2=" + id2;
//alert(page + queryString);
ajaxRequest.open("GET", page + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
The problem is that if I put the event change listener by itself, then it bugs because when the home page loads, the mainpage does not have a input yet. And if I put a script in the mainpage it doesn't execute
It is stacking because of multiple eventListeners . there only should be 1 eventListeners .
Firstly, take document.querySelector('#file').addEventListener out of bro() function.
Whenever you calling function. It is adding new change listeners without removing before one.
thus seems like bro function has no use;
This will work :
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
//OR
function bro() {
document.querySelector('#file').removeEventListener('change',(e)=>{console.log('removed listener')})
document.querySelector('#file').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
var group_id = document.getElementById('group_id').value;
var fullurl = '../backend/sendvideosandimages.php?id=' + group_id;
xhr.open('POST', fullurl, true);
xhr.onload = function() {
if (this.status == 200) {
};
};
xhr.send(fd);
}, true);
}
Remove the change event handler and then try.
You need to remove this:
document.querySelector('#file').addEventListener('change'
Right now you have two events on file upload.
Change event.
Click event.
When you click it adds a change event hence multiple uploads.
Here either you can remove change event code or remove the event listener every time you click.
Try these fixes and see if it works.

Send audio from ReactMediaRecorder to a server

I'm trying to program a Client, that can record audio data and then send it to a server.
I don't have much experience in front-end development. I was told to use React and so I'm trying to use ReactMediaRecorder (https://github.com/avasthaathraya/react-media-recorder).
render () {
return (
<ReactMediaRecorder
audio
whenStopped={blobUrl=>this.setState({audio: blobUrl })}
render={({startRecording, stopRecording, mediaBlob }) => (
<div>
<button id="recorder" className="button" onClick={startRecording}>Start Recording</button>
<button className="button" onClick={() => {stopRecording();this.upload()}}>Stop Recording</button>
<audio id="player" src={mediaBlob} controls />
</div>
)}
/>
)
}
upload() {
console.log("upload was called with blob " + this.state.audio)
//if (false) {
if (this.state.audio != null) {
console.log("got here, type of audio is " + this.state.audio)
var xhr = new XMLHttpRequest();
var filename = new Date().toISOString();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", this.state.audio, filename);
xhr.open("POST", "http://127.0.0.1:3000", true);
xhr.send(fd);
}
}
At first it seemed very straightforward. But I don't get why I can't send the mediaBlob. The formData.append says, that this.state.audio is not of type Blob. So I checked it's type in the console log, and found out it is of type stringContent. I tried to create a Blob from that by using new Blob() but failed. I also fail to find information of this type.
Does somebody know what to do?
Ok I finally got it. The mistake was, that mediaBlob is actually not blob, but a blob Url. So first we need to load it and then we can send it. I changed my upload function to:
upload(mediaBlob) {
if (this.state.audio != null) {
//load blob
var xhr_get_audio = new XMLHttpRequest();
xhr_get_audio.open('GET', mediaBlob, true);
xhr_get_audio.responseType = 'blob';
xhr_get_audio.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
//send the blob to the server
var xhr_send = new XMLHttpRequest();
var filename = new Date().toISOString();
xhr_get_audio.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data",blob, filename);
xhr_send.open("POST", "http://localhost/uploadAudio",
true);
xhr_send.send(fd);
}
};
xhr_get_audio.send();
}
}
Now it works fine.

How to upload image with tinymce using file picker handler and images_upload_handler

By default tinymce image has no browse button where you can click and see a dialog box to choose an image. In my code am trying to add image picker button to tinymce but am finding it difficult to combine it with the images_upload_handler. And lastly how do i use the success callback to update images_upload_base_path.
tinymce.init({
...
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', "postAcceptor.php");
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure("HTTP Error: " + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != "string") {
failure("Invalid JSON: " + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
I don't really understand why, but for me images_upload_handler not works as well... =(
Use file_picker_callback instead, like in this example that I found:
https://codepen.io/nirajmchauhan/pen/EjQLpV

Downloading mp3 files using html5 blobs in a chrome-extension

I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code:
var finalURL = "server1.example.com/u25561664/audio/120774.mp3";
var xhr = new XMLHttpRequest();
xhr.open("GET", finalURL, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.responseText);
var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";
saveas.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(saveas);
delete xhr;
delete blob;
delete bb;
}
}
xhr.send();
When looked in the console, the blob is created correctly, the settings look right:
size: 15312172
type: "application/octet-stream"
However, when I try the link created by the createObjectURL(),
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
I get a blank document and a warning saying
Resource interpreted as Document but
transferred with MIME type
application/octet-stream.
How can get my code to download the file correctly?
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe:
this file doesn't exist on your server
you server outputs wrong mime type for mp3 files

Categories