XMLHTTPREQUEST Problem while i append to dive in html - javascript

Hei Friends I just start to learn XMLHttpRequest
I write this code its work on console.log but when I append it to HTML it shows me Object Object i know its object but I wanna show the data inside the object in HTML HELP PLEASE
return new Promise((resolve, reject) => {
let myRequest = new XMLHttpRequest();
myRequest.onload = function () {
if (this.readyState === 4 && this.status === 200) {
resolve(JSON.parse(myRequest.responseText));
} else {
reject(Error(this.statusText));
}
};
myRequest.open("GET", apiURL, true);
// send request to API
myRequest.send();
});
};
apiGenerator("https://random-data-api.com/api/stripe/random_stripe").then(
(resulit) => {
console.log(resulit);
let newElement = document.createElement("div");
let elementText = document.createTextNode(resulit);
newElement.appendChild(elementText);
document.body.appendChild(...newElement);
},
(error) => console.log(error)
);

Related

Javascript XMLHTTPRequest .classList in response

How can I check if the response received from XMLHTTPRequest has a particular class or not?
async function swipeAction(currentElementObj) {
var cardId = currentElementObj.getAttribute("value");
var dataString = {'card': cardId};
let response = await new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open("POST", "processes/explore.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(dataString));
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// I WANT TO CHECK SOMETHING LIKE THIS
if(xhr.response.getElementById("matched").classList.contains('matched'))
alert(xhr.response.getElementById("matched").classList);
}
}
});
}
In the response received, I want to check if the element with id matched has a class name matched or not. However, the above code isn't working. What should be the proper approach here?
If you're expecting plain text/html response from the server then processing it may look like that:
async function swipeAction(currentElementObj) {
var cardId = currentElementObj.getAttribute("value");
var dataString = { card: cardId };
let response = await new Promise((resolve, reject) => {
try {
var xhr = new XMLHttpRequest();
xhr.open("POST", "processes/explore.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
// add responseType = "document" for response to be parsed into DOM
xhr.responseType = "document";
// override response mime type (in case your server sends text/plain)
xhr.overrideMimeType("text/html");
xhr.send(JSON.stringify(dataString));
xhr.onreadystatechange = function () {
// check for non-empty responseXML property
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseXML) {
const matched = xhr.responseXML.getElementById("matched");
if (!matched) return reject("Element not found in response");
if (matched) {
alert(matched.classList.contains("matched"));
resolve(true);
}
} else {
return reject("Incompatible response format");
}
};
} catch (e) {
reject(e.toString());
}
});
}

Display Javascript Ajax webservice request

I was trying to display an ajax request from a web service in my HTML.
I can display the result in the console but can not retrieve the result and then display it in my HTML.
I want to display the result of the request in "weather-result" div by clicking the "ask-weather" button.
Her is my code.
Thank everyone.
const askWeather = function(result){
var request = new XMLHttpRequest();
request.onreadystatechange = function subFunction() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
result = JSON.parse(this.responseText);
return result.current_condition.condition;
}
};
request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
request.send();
}
const ask = document.getElementById('ask-weather');
ask.addEventListener('click', function(){
const weatherResult = document.getElementById('weather-result');
weatherResult.innerHTML = askWeather();
});
<html>
<head>
<link rel="stylesheet" type="text/css" href="base.css">
</head>
<body>
<div><button id="ask-weather">Quelle est la météo sur Paris ?</button></div>
<div id="weather-result"></div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
This seems like a asynchronous/callback problem here. When the button is clicked, it sends a request somewhere and will return right away (with undefined in case of the code above - this can be checked by saving it in a variable and console.log it).
When askWeather() is called, it could return something itself. The return in request.onreadystatechange cannot return for askWeather as it's happening multiple times and later - after askWeather is done and the request is being sent.
If you pass a function a variable and set it to something new in its body, it will not be changed for the caller. That means doing result = ... does not really help, if you wanted to pass a variabel and get it set by the inner function.
A different approach is necessary to handle this. Here are a few alternatives:
To keep it as most similar to the code you had, you can set the innerHTML in the onreadystatechange function:
const askWeather = function() {
var request = new XMLHttpRequest();
request.onreadystatechange = function subFunction() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
const result = JSON.parse(this.responseText);
// set it here directly
const weatherResult = document.getElementById('weather-result');
weatherResult.innerHTML = result.current_condition.condition;
}
};
request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
request.send();
}
const ask = document.getElementById('ask-weather');
ask.addEventListener('click', function() {
askWeather();
});
Make it more general and let askWeather use a callback (call a function when it's "done"):
const askWeather = function(callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function subFunction() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
const result = JSON.parse(this.responseText);
// send the result to the passed "callback" function
callback(result.current_condition.condition);
}
};
request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
request.send();
}
const ask = document.getElementById('ask-weather');
ask.addEventListener('click', function() {
askWeather(function (result) { // this whole function is the "callback" parameter
const weatherResult = document.getElementById('weather-result');
weatherResult.innerHTML = result;
});
});
(a) Let askWeather return a promise and use it in the caller
const askWeather = () => new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
request.onreadystatechange = function subFunction() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
const result = JSON.parse(this.responseText);
// send the result to the passed "callback" function
resolve(result.current_condition.condition);
}
// not sure about the error path here, but something like this:
if (this.readyState == XMLHttpRequest.DONE && this.status != 200) {
reject(new Error("There was an error with the XMLHttpRequest!"));
}
};
request.open("GET", "https://www.prevision-meteo.ch/services/json/paris");
request.send();
});
const ask = document.getElementById('ask-weather');
ask.addEventListener('click', function() {
askWeather()
.catch((err) => weatherResult.innerHTML = err.message) // to handle possible errors, maybe?
.then((result) => { // like the callback solution, but as promise!
const weatherResult = document.getElementById('weather-result');
weatherResult.innerHTML = result;
});
});
});
(b) Additionally to the Promise solution, in newer browsers there is already async and await syntax:
ask.addEventListener('click', async function() {
try {
const result = await askWeather(); // this "pauses" until the Promise return of `askWeather` resolves (or throws an error if it doesn't)
const weatherResult = document.getElementById('weather-result');
weatherResult.innerHTML = result;
} catch (e) {
// error could be handled here
}
});
Instead of XMLHttpRequest, use the fetch API, which usually should be available if Promises are available in the browsers you support. The solution is in the comments of the original question. With most modern browsers, this should work:
ask.addEventListener('click', async () => {
const response = await fetch("https://www.prevision-meteo.ch/services/json/paris");
const result = await response.json();
const weatherResult = document.getElementById('ask-weather');
weatherResult.innerHTML = result.current_condition.condition;
});
If you don't have to support IE, I would use the fetch alternative.
I hope the other alternatives make it clear, asynchronous patterns can be resolved in JavaScript.
function getJSON(path) {
return new Promise(function(resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', path, true);
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if ((this.status >= 200 && this.status < 300) || this.status === 304) {
var response = JSON.parse(this.responseText);
resolve(response);
} else {
var error = this.statusText;
reject('Http/App Error: ' + error);
}
}
}
xhttp.onerror = processError;
xhttp.onabort = processError;
xhttp.send();
xhttp = null;
function processError(err) {
reject('Network Error: ' + err.target.status);
}
});
}
const ask = document.getElementById('ask-weather')
const weather = document.getElementById('weather-result')
const endpoint = 'https://www.prevision-meteo.ch/services/json/paris'
ask.addEventListener('click', function() {
getJSON(endpoint).then((success) => {
const response = success.current_condition.condition
weather.innerHTML = response
}, (error) => {
console.log(error)
})
})
This is a simple example using Promise. See the fiddle working.

Cannot access array element. use result of one ajax request to another ajax request

//global variables
var corpArray = new Array(); //store corp classes instances
var corpId = new Array(); //store corp id's
window.onload = init();
function init() {
getNpcCorpId();
console.log(corpId);
getCorpNames(corpId[5]);
}
//get all corporation id's from the game
function getNpcCorpId() {
let conName = new XMLHttpRequest();
conName.onload = function() {
if (this.status == 200) {
let idList = JSON.parse(this.responseText);
idList.forEach(element => {
corpId.push(element);
});
}
};
conName.open(
"get",
"https://esi.evetech.net/latest/corporations/npccorps/?datasource=tranquility",
true
);
conName.send();
}
//get corporation name
function getCorpNames(element) {
console.log(element);
let corpConn = new XMLHttpRequest();
corpConn.onload = () => {
if (this.status == 200) {
console.log(this.responseText);
}
};
corpConn.open(
"get",
`https://esi.evetech.net/latest/corporations/${element}/?datasource=tranquility`,
true
);
corpConn.send();
}
I am trying to create an eve online api, i want to use 2 global varibles to store my retrieved values (because i do not know another way) i will use a couple of functions to use the provieded eve api.I can not acces my corpId individual elements, when i console log all my array ,everything is ok,but when i want to access individual element it appears undefiend.
//global variables
var corpArray = new Array(); //store corp classes instances
var corpId = new Array(); //store corp id's
window.onload = init();
async function init() {
await getNpcCorpId();
console.log(corpId);
getCorpNames(corpId[5]); // asynchronous behaviour - let it be fix using await and async
}
//get all corporation id's from the game
function getNpcCorpId() {
return new Promise(function(resolve, reject) {
let conName = new XMLHttpRequest();
conName.onload = function() {
if (this.status == 200) {
let idList = JSON.parse(this.responseText);
idList.forEach(element => {
corpId.push(element);
});
}
resolve();
};
conName.open(
"get",
"https://esi.evetech.net/latest/corporations/npccorps/?datasource=tranquility",
true
);
conName.send();
});
}
//get corporation name
function getCorpNames(element) {
console.log(element);
let corpConn = new XMLHttpRequest();
corpConn.onload = () => {
if (this.status == 200) {
console.log(this.responseText);
}
};
corpConn.open(
"get",
`https://esi.evetech.net/latest/corporations/${element}/?datasource=tranquility`,
true
);
corpConn.send();
}
This is due to asynchronous behaviour - in simple terms - when you
call getNpcCorpId() it is a http request it will take some time to
execute but next line run immediately so at that point of time corpId
is still blank. So to fix this issue you can use await that will makes
JavaScript wait until the promise returns a result.
Hope this helps you !

JavaScript: Prepend element to DOM and inherit event handler

I have a <textarea> and a <button> inside of a <form>. When submitted, I call e.preventDefault() and submit the form via AJAX. From there I return the query and PREPEND at information inside of a <div> at the top of this list.
Also, I have given each item the ability to be deleted, which is instant on the client side but also submits a form via AJAX to be completely removed. This is sort of working.
I am able to:
Have a blank screen (no items added), create one and delete it no problems
Have blank screen, add two items, delete the NEWEST item with no problems but deleting the second item (which was the first, or oldest item) returns an error. It's trying to delete itself and the NEWEST item. So if I have three, it will delete itself and the newest, leaving item #2 all alone. This just gets worse the more items that are added.
What I need to do
Have newly Prepended element inherit the event handler
Only remove the item that is selected
Code Explanation
When the user loads the page, items that are stored in the database are immediately queried and added to the screen.
Go ahead and find const delPostFunc in the first code example. This is an anonymous function that is called immediately, to ensure that any items that are initially added to the screen are assigned the click event handler.
When a user submits a new item via submitPostBtn.addEventListener('click', e => {, at the bottom of the first example, two calls are made. One to const submitPost, AJAX in the second example, and const returnNewestPost, AJAX in the second example. This returnNewestPost call returns some DATA from the database, which just so happens to be the newest item inserted, and then it PREPENDS this item to the top of the list, displayPostWrapper.prepend(newPostDiv); and finally calls the delPostFunc(); function in an attempt to reassign the event handler to newly inserted items. This is because innerHTML removes any event handlers that are supposed to be on an element, or that is what I am lead to believe.
JavaScript
// DELETE POST VARIABLES
let deletePostBtn = document.querySelectorAll('button[name="delete_post"]');
const displayPostWrapper = document.querySelector('.col-8.pt-4');
let displayPostSection = document.querySelectorAll('.col-8.pt-4 .row');
let postID = document.querySelectorAll('#delete-post-id');
// SUBMIT POST VARIABLES
const submitPostBtn = document.querySelector('#submit-post-button');
const submitPostID = document.querySelector('#submit-post-id');
const submitPostContent = document.querySelector('#submit-post-content');
const submitPostName = document.querySelector('#submit-post-name');
// MAKING THE CALL TO DELETE THE POST
const delPostFunc = () => {
console.log(deletePostBtn);
deletePostBtn = document.querySelectorAll('button[name="delete_post"]');
console.log(deletePostBtn);
if (deletePostBtn) {
for (let i = 0; i < deletePostBtn.length; i++) {
deletePostBtn[i].addEventListener('click', e => {
e.preventDefault();
postID = document.querySelectorAll('#delete-post-id');
displayPostSection = document.querySelectorAll('.col-8.pt-4 .row');
console.log(postID[i].value);
// ${postID[i]} comes from `const postID` at the top
deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID[i].value}`);
console.log(deletePostBtn);
displayPostSection[i].remove();
console.log(deletePostBtn);
});
}
}
}
// CALL `delPostFunc()` FOR THE INITIAL `deletePostBtn` ON SCREEN
delPostFunc();
// MAKING CALL TO SUBMIT NEW POST
if (submitPostBtn) {
submitPostBtn.addEventListener('click', e => {
e.preventDefault();
// SUBMIT POST
submitPost('http://localhost/mouthblog/ajax/submit_post.ajax.php',
`id=${submitPostID.value}&name=${submitPostName.value}&content=${submitPostContent.value}`)
.then(() => {
// RETURN THAT SAME POST
returnNewestPost('http://localhost/mouthblog/api/newest_post.php')
.then(data => {
// INSERT POST INTO DOM
const newPostDiv = document.createElement('div');
newPostDiv.setAttribute('class', 'row');
newPostDiv.innerHTML = `
<article class="col-10 offset-1">
<h2 class="h2">${data.user_name}</h2>
<small>${data.date_created}</small>
<form action="//localhost/mouthblog/blog.php" method="POST">
<button class="btn btn-danger" name="delete_post" type="submit">DELETE</button>
<input id="delete-post-id" name="post_id" type="hidden" value="${data.id}">
</form>
<hr>
<p class="lead">${data.content}</p>
</article>
`;
console.log(`INSERTING ${data.id}`);
displayPostWrapper.prepend(newPostDiv);
console.log(`INSERT ${data.id} COMPLETE`);
// GIVE THE `newPostDiv`'s `delete button` THE CLICK EVENT HANDLER
console.log(`RUNNING delPostFunc()`);
delPostFunc(); // BOOM!
console.log(`delPostFunc() COMPLETE`);
});
});
});
}
These are the promises for the AJAX just incase
// GET REQUEST TO RETRIEVE EVERY POST
const get = (url) => {
return new Promise((resolve, reject) => {
const xhttp = new XMLHttpRequest();
xhttp.open('GET', url, true);
xhttp.onload = () => {
if (xhttp.status == 200) {
resolve(JSON.parse(xhttp.response));
} else {
reject(xhttp.statusText);
}
};
xhttp.onerror = () => {
reject(xhttp.statusText);
};
xhttp.send();
});
}
// DELETE SPECIFIC POST
const deletePostPromise = (url, postID) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('if (xhr.status == 200)');
resolve();
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(postID);
});
}
// SUBMIT A NEW POST
const submitPost = (url, user_id, user_name, content) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('resolving');
resolve();
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(user_id, user_name, content);
});
};
// RETURN THE NEWEST BLOG POST
const returnNewestPost = (url) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('resolving');
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.send();
});
}
The simplest answer to this question is to rewrite the script using Event Delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Compare the script from the OP and compare this one. The rewritten script has less code, less loops, less variables and is a lot easier to maintain and read through.
If you would like to compare specifics, event delegation starts on the line with if (displayPostWrapper && submitPostBtn) {
Re-written JS
const submitPostBtn = document.querySelector('#submit-post-button');
const submitPostID = document.querySelector('#submit-post-id');
const submitPostContent = document.querySelector('#submit-post-content');
const submitPostName = document.querySelector('#submit-post-name');
const displayPostWrapper = document.querySelector('.col-8.pt-4');
// GET REQUEST TO RETRIEVE EVERY POST
const get = (url) => {
return new Promise((resolve, reject) => {
const xhttp = new XMLHttpRequest();
xhttp.open('GET', url, true);
xhttp.onload = () => {
if (xhttp.status == 200) {
resolve(JSON.parse(xhttp.response));
} else {
reject(xhttp.statusText);
}
};
xhttp.onerror = () => {
reject(xhttp.statusText);
};
xhttp.send();
});
}
// DELETE SPECIFIC POST
const deletePostPromise = (url, postID) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('if (xhr.status == 200)');
resolve();
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(postID);
});
}
// SUBMIT A NEW POST
const submitPost = (url, user_id, user_name, content) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('resolving');
resolve();
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(user_id, user_name, content);
});
};
// RETURN THE NEWEST BLOG POST
const returnNewestPost = (url) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('resolving');
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.send();
});
}
// MAKING THE CALL TO DELETE THE POST
if (displayPostWrapper && submitPostBtn) {
displayPostWrapper.addEventListener('click', e => {
if (e.target && e.target.nodeName == 'BUTTON') {
e.preventDefault();
const row = e.target.parentElement.parentElement.parentElement;
const form = e.target.parentElement;
const postID = e.target.parentElement.childNodes[3].value;
deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID}`);
row.remove();
} // if
}); // click event
submitPostBtn.addEventListener('click', e => {
e.preventDefault();
submitPost('http://localhost/mouthblog/ajax/submit_post.ajax.php',
`id=${submitPostID.value}&name=${submitPostName.value}&content=${submitPostContent.value}`)
.then(() => {
returnNewestPost('http://localhost/mouthblog/api/newest_post.php')
.then(data => {
console.log(data);
const newPost = document.createElement('div');
newPost.setAttribute('class', 'row');
newPost.innerHTML = `
<article class="col-10 offset-1">
<h2 class="h2">${data.user_name}</h2>
<small>${data.date_created}</small>
<form action="//localhost/mouthblog/blog.php" method="POST">
<button class="btn btn-danger" name="delete_post" type="submit">DELETE</button>
<input id="delete-post-id" name="post_id" type="hidden" value="${data.id}">
</form>
<hr>
<p class="lead">${data.content}</p>
</article>
`;
displayPostWrapper.prepend(newPost);
}) // then
}) // then
}); // click event
} // if

How to handle XMLHttpRequests in a redux action?

I have a redux-form that is passing props to my action. The property this.props.userImages[0] is an image file from a file input on that form. I'm then taking that image and making and XMLHttpRequest to Cloudinary which generates a url for that image. Once I receive the url data (xhr.responseText), I'd like to then merge it with my other props to that I can then post all of my props to an API (all form info + newly created image URL).
I know that I have to wait for my request to generate a url to resolve, but having issues with getting it right before I can pass it onto my other function which can take that info and merge it in with props before posting to my API.
//..
function generateUrl(props) {
// Grabs image file from my form's file input and uploads
// to cloudinary service so that a URL can be generated
const cloudinaryURL = 'https://api.cloudinary.com/v1_1/<my_name>/image/upload';
const apiKey = 'secret_key';
const uploadPreset = 'test_preset';
const data = new FormData();
data.append('file', props.userImages[0]);
data.append('upload_preset', uploadPreset);
data.append('api_key', apiKey);
const xhr = new XMLHttpRequest();
xhr.open('POST', cloudinaryURL, true);
xhr.send(data);
xhr.onReadyStateChange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
return JSON.parse(xhr.responseText);
}
};
return xhr.onReadyStateChange();
}
export function createReview(props) {
const imageUrl = generateUrl(props);
const mergedProps = //...
// Here I'd like to merge my newly generated
// url back into props before I post to my API like so...
const request = axios.post(`${REQUEST_URL}/api`, mergedProps)
return {
type: CREATE_REVIEW,
payload: request
}
};
Any and all help is greatly appreciated.
This has nothing to do with promises in the context of your example XMLHttpRequest based code.
The assumption your making is that the callback assigned to onReadyStateChange does something with it's return value. Instead anything returned from that function is dutifully ignored.
What you want is to pass the value onward through another callback.
function generateUrl(props, callback) {
// Do things here
xhr.onReadyStateChange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(JSON.parse(xhr.responseText));
}
};
}
generateUrl(props, (response) => {
const mergedProps = // Use response as expected.
});
Since you mentioned promise and your using ES2015 we can convert this to actually use promises which is probably what you wanted to begin with.
function generateUrl(props) {
return new Promise((resolve, reject) => {
const cloudinaryURL = 'https://api.cloudinary.com/v1_1/<my_name>/image/upload';
const apiKey = 'secret_key';
const uploadPreset = 'test_preset';
const data = new FormData();
data.append('file', props.userImages[0]);
data.append('upload_preset', uploadPreset);
data.append('api_key', apiKey);
const xhr = new XMLHttpRequest();
xhr.onReadyStateChange = () => {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.responseText);
} else {
reject(new Error(`Failed HTTP request (${xhr.status})`));
}
};
xhr.onerror = reject;
xhr.open('POST', cloudinaryURL, true);
xhr.send(data);
});
}
generateUrl(props)
.then(JSON.parse)
.then(results => {
// Do something with response
})
.catch(error => {
// Do something with the error
});

Categories