XMLHttpRequest with promises return a null response - javascript

I'm trying to call ajax request without using jquery. By using ECMA Script6:
var promise1 = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
var url = urls.urlListChapters.replace(0, specificationId);
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 200) {
alert(xhr.response);
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error("Network error"));
};
xhr.send();
});
promise1.then(function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
I get as response "null". However, with my ol jquery method, I do get the list of objects.
$.ajax({
url: urls.urlListChapters.replace(0, specificationId),
dataType: 'json',
method: 'GET',
})
.done(function(data) {
var data = JSON.parse(data);
console.log(data);
alert(1)
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
alert('WHAT!');
});
Is there something I'm missing?

Related

I want to convert a jquery function to javascript

I want to convert a jquery function into a javascript function:
window.parent.$.ajax({
type: 'GET',
url: "http://localhost:3063/corsService/GetCultureInformation",
contentType: "application/json",
dataType: "json",
success: function (data) {
numberDecimalDigit = data.NumberDecimalDigits;
},
async: false
});
I converted it to:
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:3063/corsService/GetCultureInformation', false);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
numberDecimalDigit = data.NumberDecimalDigits;
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
but I have errors:
1: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
2: NetworkError
//Better use promises, as it reduces biolerplate heavy code of XMLhttp request provides.
function loadjson(file) {
return new Promise((resolve, reject) => {
return fetch(file).then((response) => {
if (response.ok) {
resolve(response.json());
} else {
reject(new Error("error"));
}
});
});
}
var newFile=loadjson("https://api.postalpincode.in/pincode/110001").then((data) => {
console.log(data);
});

PHP backend with JS xHTMLRequest frontend

In JS, I wanted to create a function that made a xHTMLRequest to a backend PHP server, problem is I want JS to wait for the response, otherwise it will display 'undefined'.
function xhrReq(method, args) {
let xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(args);
xhr.onreadystatechange = ()=> {
if(xhr.readyState == 4) {
return xhr.response;
}
}
How can I make this function return the response value?
You can use fetch in a async function:
(async () => {
try {
//const args = ...;
var headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
const response = await fetch('http://localhost/example/php/example.php', {
method: 'POST', // or other
headers,
body: args
});
} catch (err) {
//process error
}
})()
or you can promisify your function :
function xhrReq(method, args) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(Error(`XHR request failed. Error code: ${xhr.statusText}`));
}
};
xhr.onerror = function() {
reject(Error('There was a network error.'));
};
xhr.send(args);
});
}
And use it in a async function (or use promise) to get the response.

put the data from an api link using this function and console.log it

I want to use a variable which has the JSON data to later parse and stringify it
all i want now is to see the actual array of objects in the console!
console.log(fetchJSON('url'));
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status < 400) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
}
I expect the output of console.log(fetchJSON('url'));
to be
Try this:
fetchJSON('url', function(result) {
console.log(result);
});
Your function fetchJSON is returning a callback function. If you want to return just the result change
this
cb(null, xhr.response);
to:
return xhr.response;

Promise returning undefined after sending value to the server

I just started making use of the promise function in javascript, and i do like it, but i am running into an issue.
I am getting a value from a promise object, and then sending the response back to the server in an asynchronous promise function. When i send the value back to the server, and try to see what the value is, it returns undefined.
var xhr = new XMLHttpRequest();
function createFirstChannel(method, rippleApi) {
return new Promise(function (resolve, reject) {
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4 ) {
var hashValue = resolve(JSON.parse(xhr.responseText));
}
else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(json);
});
}
A value gets returned from the first function which i am using in the next promise function
async function createChannel(method, url) {
var datums = await createFirstChannel(method, url);
//method to return hash value from json request
for (var key in datums) {
var tx_json = datums[key]['json'];
datums = (json['hash']);
console.log(datums);
}
//creating the json request to send back out again using POST METHOD
var channel= {
"method": "tx",
"par": [{
"transaction": datums
}]
}
var jsonPayee = JSON.stringify(channel);
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4) {
users = JSON.parse(xhr.responseText);
}
};
xhr.send(jsonPayee);
return users;
}
createChannel(method, url).then(datums => {
console.log(datums);
}).catch(function (err) {
console.error('Sorry There Was An Error!', err.statusText);
});
i get "undefined" response at console.log. is there any way to resolve this error? Thanks for the help

How to unchain chained anonymous functions in Javascript?

Is there a way to unnest (or unchain) the chained anonymous functions below? I include my try after the script with nested anonymous functions. I want to define separately each function defined anonymously on its own to see clearly and understand where each function starts and ends and what they do. Thanks.
A script with nested anonymous functions that I want to separate (taken from here):
<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
var firstParagraph = response.dom;
//}); moved to end to get the variable firstParagraph
var formData = new FormData();
formData.append("url", tab.url);
formData.append("title", tab.title);
formData.append("pitch", firstParagraph);
//formData.append("user_tag_list", "tag1, tag2");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}else{
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
}
}
};
xhr.send(formData);
}); //chrome.tabs.sendRequest
});
});
</script>
</html>
My try to unnest anonymous function and reconstruct the script:
functionForSendRequest = function (response) {var firstParagraph = response.dom;
var formData = new FormData();
formData.append("url", tab.url);
formData.append("title", tab.title);
formData.append("pitch", firstParagraph);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4){
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText({text: "done" });
setTimeout(function(){
chrome.browserAction.setBadgeText({text: ""});}, 2000);}
else{console.log("connection error");
chrome.browserAction.setBadgeText({text: "ERR"});}}};
xhr.send(formData);}}
argumentToGetSelected = chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, functionForSendRequest()}
...
functionForGetSelected = function (tab) {chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, *function for getSelected goes here*)}
To see the logic clearly, instead of "unchaining" them why not just try to practice good indentation. Then you can visually follow each method according to its indentation level. Like this:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
var firstParagraph = response.dom;
var formData = new FormData();
formData.append("url", tab.url);
formData.append("title", tab.title);
formData.append("pitch", firstParagraph);
//formData.append("user_tag_list", "tag1, tag2");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
} else {
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
}
}
};
xhr.send(formData);
}); //chrome.tabs.sendRequest
}); // chrome.tabs.getSelected
}); // chrome.browserAction.onClicked.addListener
Or, if you want to "unchain", the only really obvious thing to do is to define that inner callback separately, like this:
var handle_request = function(response) {
var firstParagraph = response.dom;
var formData = new FormData();
formData.append("url", tab.url);
formData.append("title", tab.title);
formData.append("pitch", firstParagraph);
//formData.append("user_tag_list", "tag1, tag2");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
} else {
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
}
}
};
xhr.send(formData);
}
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, handle_requeest);
});
});

Categories