Why my variable not getting assigned value from JS function? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 months ago.
** Placing My actual JS snippet"
I have a small JS function in one JS file as below
function interest(customerRef) {
try {
var customerInterest = "";
var baseUrl="https://test/"
var url = baseUrl+customerRef
var username = "username";
var password = "password";
var request = new XMLHttpRequest();
request.open("GET", url);
request.setRequestHeader("Authorization", "Basic " + btoa(username+":"+password))
request.send()
request.onload=()=>
{
if(request.status==200)
{
var guestJson = JSON.parse(request.response);
var sessions = guestJson.sessions || [];
var interest = sessions.filter(session => session.events)
.flatMap(session => session.events)
.filter(event => event.type === "SEARCH")
.map(event => event.arbitraryData.interest)[0];
customerInterest = interest;
alert("---"+customerInterest);
}
else
{
console.log(`error ${request.status} ${request.statusText}`)
}
}
alert(customerInterest);
return customerInterest;
}
catch (error) {
console.error(error);
}
}
I am calling the above function in my HTML file as below
customerRef = "6a789727"
var interest1 = "";
interest1 = interest(customerRef);
console.log(interest1);
I am not getting any value in "console.log(interest1)" or "alert(customerInterest);" before the return. But i am getting the expected value in "alert("---"+customerInterest);"

No, you'll get an error, not just undefined.
Running
var test = "";
test = test()
console.log(test)
will yield an
Uncaught TypeError: test is not a function
at line 2, since you just defined test to be a string ("") instead of a function you could call.
Instead, try something like:
function greet() {
return "Hi";
}
var test = "";
test = greet();
console.log(test);
If you evaluate this in the console, this will print out
Hi
undefined
; the latter undefined comes from the return value of console.log();

Related

pass data response from xhr to html element

I have input element in my page, and i receive data from XMLHttpRequest when i click button.
I try to pass some data to html element, the data receive correctly but i can't pass to element.
this is my code
<input type="text" value="5" id="a" />
<script>
(function() {
let origOpen = XMLHttpRequest.prototype.open;
let a = 0;
XMLHttpRequest.prototype.open = function() {
console.log('request started!');
this.addEventListener('load', function() {
console.log('request completed!');
console.log(this.readyState); //will always be 4 (ajax is completed successfully)
console.log((JSON.parse(this.responseText)).input.a); // result = 20
a = parseInt((JSON.parse(this.responseText)).input.a);
$("#a").val(a); // not work
$("#a").setAttribute('value',a); // error: TypeError: $(...).setAttribute is not a function
document.getElementById("a").value = a; // error: TypeError: document.getElementById(...) is null
$("#a").value = a; // not work
});
origOpen.apply(this, arguments);
};
})();
</script>
The problem is in your request. Providing you really want to use the relict that XHR is it should be refactored this way:
const input = document.getElementById('a');
const myReq = new XMLHttpRequest();
myReq.onload = function() {
const data = JSON.parse(this.responseText);
input.value = data;
};
myReq.onerror = function(err) {
console.log(err);
};
myReq.open('get', '[your url]', true);
myReq.setRequestHeader('Accept', ' application/json');
myReq.send();
I have tested this code and it works with a dumb api.

Javascript function run with order [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How do I promisify native XHR?
(6 answers)
Closed 3 years ago.
i have some problem with ordering my functions.
i have 2 function. Two of them to http requests.
what a scenario?
on first request i get some response and in this response i'm getting some string and set it to some variable.
on second request i'm adding this string to my request url.
but my second request working before then in first request response when i set my variable.
because of that i'm getting undefined value of my variable.
I understand this is sync, async problem but how i can resolve this issue ?
it's my variable which i will add end of the second request url.
var urlString = '';
this is my first request:
var requestone = new XMLHttpRequest();
requestone.onload = function () {
if (requestone.status >= 200 && requestone.status < 300) {
var data = requestone.response;
data = JSON.parse(data);
urlString = data.Key
} else {
console.log('fail')
}
};
requestone.open('GET', 'apiurl');
requestone.send();
this is my second request:
var requesttwo = new XMLHttpRequest();
requesttwo.onload = function () {
if (requesttwo.status >= 200 && requesttwo.status < 300) {
var data = requesttwo.response;
} else {
console.log('fail')
}
};
requesttwo.open('GET', 'apiurl' + urlString);
requesttwo.send();
You can do this in 2 ways, using promise, or integrate the second request inside the request1:
var requestone = new XMLHttpRequest();
requestone.onload = function () {
if (requestone.status >= 200 && requestone.status < 300) {
var data = requestone.response;
data = JSON.parse(data);
requesttwo.open('GET', 'apiurl' + data.Key);
requesttwo.send();
} else {
console.log('fail')
}
};
requestone.open('GET', 'apiurl');
requestone.send();

Three statuses being returned in Network tab

So I am consuming the Domainer API using this JavaScript code in my script.js:
const DOMAINRURLSTATUS = 'https://domainr.p.mashape.com/v2/status';
const DOMAINRKEY = '<api-key>';
// get data from domainr api
function getDataFromApi(value, callback) {
const QUERY = {
'mashape-key': DOMAINRKEY,
domain: `${value}.com,${value}.net,${value}.org,${value}.biz`
};
$.getJSON(DOMAINRURLSTATUS, QUERY, callback);
}
// create the code that will display for the domain availability
function renderResult(result) {
const OUTPUT = $('#domainContainer');
OUTPUT.prop('hidden', false);
// while (result.domain === ".net" || ".com" || ".biz" || ".org"){
// return `<div class="domainUnavail">LOADING<span class="sold">LOADING</span></div>`;
// }
if (result.summary == 'inactive') {
return `<div class="domain">${
result.domain
}<span class="buyButton"><a href="https://www.namecheap.com/domains/registration/results.aspx?domain=${
result.domain
}" target="_blank">Buy it!</a></span></div>`;
} else if (result.summary == 'active') {
return `<div class="domainUnavail">${
result.domain
}<span class="sold">Unavailable</span></div>`;
} else {
return `<div class="domainUnavail">${
result.domain
}<span class="sold">Unavailable</span></div>`;
}
}
// render results to page (will bring in renderResult code from above.)
function displayDomainResults(data) {
const RESULTS = data.status.map((item, index) => renderResult(item));
$('#domainResults').html(RESULTS);
}
// script for random name generation
function get_new_name() {
const OUTPUT = $('#nameResult');
OUTPUT.prop('hidden', false);
$('#nameResult').html(`<img src="ajax-loader.gif">`);
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
// get value from drop down
var minlen = document.getElementById('js-dropValue').value,
maxlen = document.getElementById('js-dropValue').value,
param = 'min=' + minlen + '&max=' + maxlen;
// Get data from name generator
xmlhttp.open(
'GET',
'https://cors-anywhere.herokuapp.com/https://uzby.com/api.php?' + param,
true
);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('nameResult').innerHTML = xmlhttp.responseText;
}
const THISQUERY = xmlhttp.responseText;
getDataFromApi(THISQUERY, displayDomainResults);
};
xmlhttp.send();
return false;
}
I would get three requests on my Network tab and I was unsure why. I tried different refactors until I decided to reach out to the Domainer team and they told me that the problem was with my code and not their API, specifically the onreadystatechange in my XMLHttpRequest handler.
They said, since I am using jQuery, to use its built-in ajax method instead of using XMLHttpRequest directly.
So I followed their suggestion and refactored the code like so:
const DOMAINRURLSTATUS = "https://domainr.p.mashape.com/v2/status"
const UZBYURL = "https://cors-anywhere.herokuapp.com/https://uzby.com/api.php?"
var DOMAINRKEY = config.DOMAINRKEY;
// get data from domainr api
function getDataFromDomainrApi(value, callback) {
const OUTPUT = $('#domainContainer');
OUTPUT.prop('hidden', false);
$('#domainResults').html('<br><img src="ajax-loader-light.gif" alt="ajax-loader">');
const QUERY = {
"mashape-key": DOMAINRKEY,
domain: `${value}.com,${value}.net,${value}.org,${value}.biz`
}
$.getJSON(DOMAINRURLSTATUS, QUERY, callback)
.fail(function(){alert("Domain connection not working?")});
}
// create the code that will display for the domain availability
function renderResult(result) {
if (result.summary == "inactive") {
return `<div class="domain">${result.domain}<span class="buyButton">Buy it!</span></div>`;
} else if (result.summary == "active") {
return `<div class="domainUnavail">${result.domain}<span class="sold">Unavailable</span></div>`;
} else {
return `<div class="domainUnavail">${result.domain}<span class="sold">Unavailable</span></div>`;
}
}
// render results to page (will bring in renderResult code from above.)
function displayDomainResults(data) {
const RESULTS = data.status.map((item, index) => renderResult(item));
$('#domainResults').html(RESULTS);
}
//Wait for user to click "create my name" button
function watchSubmit() {
$('.js-search-form').submit(event => {
event.preventDefault();
//unhide name section
$('#domainResults').html("");
const NAMEOUTPUT = $('#nameResult');
NAMEOUTPUT.prop('hidden', false);
// add loading image for latency
$('#nameResult').html('<img src="ajax-loader.gif" alt="ajax-loader">');
// set variables for get request
var minlen = $('#js-dropValue').val();
var maxlen = $('#js-dropValue').val();
var param = `min=${minlen}&max=${maxlen}`;
//Get random name result
$.ajax({
type: 'GET',
url: `${UZBYURL}${param}`,
success: function(result) {
const NAME = result;
$('#nameResult').html(NAME);
getDataFromDomainrApi(result, displayDomainResults);
},
error: function() {
alert('error loading names');
}
});
});
}
$(watchSubmit);
It did not change the behavior inside of the Network tab. Any suggestions as to what could be wrong with either versions of my code OR which version is a better solution? Regardless of whether or not it will solve the aforementioned issue? Thank you.

Why is this an unreachable code?

I'm calling the function getKeywords from another function and got an Unrecheable code detected section and don't understand why. Any help?
var env = require('dotenv').config();
var request = require('request')
var getKeywords = function(){
request.get('URI', //URI IS CORRECT IN MY CODE
function(err, httpResponse, body){
if(err){ //UNREACHABLE CODE DETECTED
console.error("request.post Error:", err);
return false;
} //UNREACHABLE CODE DETECTED
else{
console.log('Im here');
return JSON.parse(httpResponse.body).keywords;
}
});
}
module.export = getKeywords;
Here is the calling code.
var getKeywords = require('./getKeywords.js');
var keywords = new getKeywords();
var env = require('dotenv').config();
var difflib = require('difflib');
var postMention = require('./postMention.js');
var detection = function(obj, i){
var keyword = keywords[i];
var mentionObject = {
//some json
//postMention(mentionObject);
}
}
module.exports = detection;
Some tools have the ability to analyze every call to your function. It may be possible that all the places in your code that call the function you never set err parameter to true.

SCRIPT65535: Invalid calling object in IE9

I am new to javascript. I am facing an issue in someone else written code. They have created a security.js file and they are trying to overwrite xmlHTTPRequest (am not sure). attaching the code here.
(function () {
function getXHRObj(baseObj){
var Impl = function(){
this.onreadystatechange = null;
return this;
};
//Impl.prototype.onreadystatechange = null;
// set the prototype of the new constructor
Impl.prototype = baseObj;
//Impl.prototype.constructor = Impl; // does not work in IE
// the object to be returned
var retObj = new Impl();
function isHTTPReq(url){
if(url){
var colIndx = url.indexOf('://');
if((colIndx < 0)
|| (url.substr(0, colIndx).toLowerCase().indexOf('http') == 0))
return true;
}
return false;
}
// customize open to add token in URL
// even POST request should do this since POST may not always have key=value&... data format
retObj.open = function(method, URL, async, user, pwd){
if(isHTTPReq(URL)){
var prefix = (URL.indexOf('?') < 0)? '?' : '&';
URL += (prefix + window.csrfToken);
}
//alert('making ajax to - ' + URL);
Impl.prototype.open(method, URL, async, user, pwd);
};
// customize send
retObj.send = function(body){
/* Register the handler just before "send" to allow reuse of same object */
Impl.prototype.onreadystatechange = function(){
//alert('Impl.prototype.readyState- '+ Impl.prototype.readyState);
// copy the properties to return object
if(Impl.prototype.readyState)
retObj.readyState = Impl.prototype.readyState;
if(Impl.prototype.readyState == 4){
if(Impl.prototype.status)
retObj.status = Impl.prototype.status;
if(Impl.prototype.statusText)
retObj.statusText = Impl.prototype.statusText;
if(Impl.prototype.responseText)
retObj.responseText = Impl.prototype.responseText;
if(Impl.prototype.responseXML)
retObj.responseXML = Impl.prototype.responseXML;
//alert('xml done');
}
// publish event to return object handler
if(retObj.onreadystatechange){
//alert('invoking handler - \n' + retObj.onreadystatechange);
retObj.onreadystatechange();
}else{
//alert('no handler');
}
};
Impl.prototype.send(body);
};
// delegate other methods
/* Redefinition is necessary because IE does not allow inheritance
from native objects */
retObj.abort = function() {
Impl.prototype.abort();
};
retObj.setRequestHeader = function(hdr, val){
Impl.prototype.setRequestHeader(hdr, val);
};
retObj.getResponseHeader = function(hdr){
return Impl.prototype.getResponseHeader(hdr);
};
retObj.getAllResponseHeaders = function(){
return Impl.prototype.getAllResponseHeaders();
};
return retObj;
}
// redefine the XMLttpRequest to use custom definition
if(window.XMLHttpRequest){
var Base_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function(){
//alert('in new XHR');
return getXHRObj(new Base_XMLHttpRequest());
};
}
// redefine the ActiveXObject to use custom definition
if(window.ActiveXObject) {
var Base_ActiveXObject = window.ActiveXObject;
window.ActiveXObject = function(objType){
//alert('in new ActiveXObj for - ' + objType);
if((objType.toLowerCase() != "microsoft.xmlhttp")
&&(objType.toLowerCase().indexOf("msxml2.xmlhttp") < 0)){
// return the standard impl for non-ajax objects
return new Base_ActiveXObject(objType);
}else{`enter code here`
//alert('returning new impl for ' + objType);
return getXHRObj(new Base_ActiveXObject(objType));
}
};
}
})();
This code is working fine in IE7 & 8, but this is giving error in all other browsers.
IE9 error -
SCRIPT65535: Invalid calling object
security.js, line 71 character 4
Error is pointing to this.onreadystatechange = null;
var Impl = function(){
this.onreadystatechange = null;
return this;
};
Appreciate immediate help.
Thanks!

Categories

Resources