pass data response from xhr to html element - javascript

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.

Related

How to stop number being converted to string in xmlHttpRequest?

How do I stop a number being converted to a string when adding an element to a JSON file on a server using xmlHttpRequest?
The following code updates my .json file with the element but the number (var importance) is a string by the time it arrives at the server... and I can't work out why.
This is where I format my input data and create the xmlHttpRequest.. (script.js):
btnSubmit.onclick = submitTask;
function submitTask() {
inputTask = document.querySelector('#task');
inputImportance = document.querySelector('#importance');
var task = inputTask.value;
var importance = Number(inputImportance.value);
console.log("User Input: ",task, importance);
//Setup XML HTTP Request
var xhr = new XMLHttpRequest();
xhr.open('POST', api_url_add +'/'+ task +'/'+ importance, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//Receive response from server.
xhr.onload = function() {
response = JSON.parse(xhr.response);
console.log(response);
}
xhr.send();
}
And this is the server side code (server.js):
// ADD task to the list (task, importance)
app.post('/add/:task/:importance?', addTask);
function addTask(request, response) {
var data = request.params;
console.log('Submitted to server:','\n', data);
var task = data.task;
var importance = Number(data.importance);
var reply;
if (!importance) {
var reply = {
msg: "Importance value is required."
}
} else {
var element = data;
tasks['taskList'].push(element);
fs.writeFile('tasks.json', JSON.stringify(tasks, null, 2), function(err){
console.log('all done')
})
response.send(reply);
}
}
Thanks for all of your help.

Creating global VAR in functions

So I'm having trouble with getting a VAR in a function to be global, I have tried the following resources:
What is the scope of variables in JavaScript?
My previous question was marked as a duplicate but after reviewing the link above it did not help with my issue.
Here is my previous question:
So I'm using OpenTok to create a online conferencing tool and need to grab the session details from an API on a different server. I've created a php script on the other server that grabs session information based on the session id provided by a URL parameter. I know that the php script and most of the JavaScript is working correctly because when I console.log data from the parsed JSON it prints the correct information. However when I try to put the variables into the credentials area I get the following error:
ReferenceError: thesession is not defined
Here is the code used to get the JSON from a PHP script on a separate server:
var url_string = window.location.href;
var url = new URL(url_string);
var session = url.searchParams.get("s");
if (session == '') {
window.location.replace("http://www.google.com");
}
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON('http://192.168.64.2/api/meeting/?uid=' + session,
function(err, data) {
if (err !== null) {
console.log('Error');
}
var thesession = data.sessionID;
var thetoken = data.token;
console.log(thesession);
console.log(thetoken);
});
let otCore;
const options = {
credentials: {
apiKey: "####",
sessionId: thesession,
token: thetoken
},
And here is a screenshot of the console:
The top console log is "thesession" and the second console log is "thetoken". I have tried looking up the error but can't quite find one with the same usage as mine.
The desired outcome would be that I could using the data from the parsed JSON and use the result as the credentials e.g. data.sessionID which is bound the the VAR thesession.
I know this might be a scope issue, but I'm not sure how I could alter the code to make it work as intended.
Any help would be much appreciated, this one has really got me stumped :)
How would I alter the scope to get the desired function? I have reviewed the link that was given on the previous question, but this didn't help me with my issue.
var thesession = data.sessionID;
Is defined within its execution context, which is the callback function you've passed to getJSON.
One step in the right direction is to reverse the assignment. Assign 'thesession' to the options object within the scope where 'thesession' exists.
const options = {
credentials: {
apiKey: "####",
sessionId: null,
token: thetoken
}
};
getJSON('http://192.168.64.2/api/meeting/?uid=' + session,
function(err, data) {
if (err !== null) {
console.log('Error');
}
var thesession = data.sessionID;
var thetoken = data.token;
console.log(thesession);
console.log(thetoken);
options.credentials.sessionId = thesession;
});
However, it's important to realize that your program is not going to wait for this assignment. It will send the getJSON request, and then continue processing. Your options object won't have a sessionId until the getJSON call finishes and its callback has been invoked.
This would be a good opportunity to delve into Promises, which will help you better understand how to handle the non-blocking nature of javascript.
Your problem is that this line var thesession = data.sessionID is scoped within the function function(err, data) { ... }. In order to allow two functions to use the same variable, you need to make sure that the variable isn't declared somewhere they don't have access to.
It's the difference between this:
function func1() {
var x = 3
}
function func2() {
console.log(x)
}
func1();
func2();
and this:
var x;
function func1() {
x = 3
}
function func2() {
console.log(x)
}
func1();
func2();
Similarly, if you declare var thesession; at the start of your script (or at least outside that other function) then just set it with thesession = data.sessionID, your final part will have access to your variable thesession.
Edit
In context:
var url_string = window.location.href;
var url = new URL(url_string);
var session = url.searchParams.get("s");
var thesession;
var thetoken;
if (session == '') {
window.location.replace("http://www.google.com");
}
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON('http://192.168.64.2/api/meeting/?uid=' + session,
function(err, data) {
if (err !== null) {
console.log('Error');
}
thesession = data.sessionID;
thetoken = data.token;
console.log(thesession);
console.log(thetoken);
});
let otCore;
const options = {
credentials: {
apiKey: "####",
sessionId: thesession,
token: thetoken
},
As a side-note - I'd also recommend not using var and instead just using let of const, depending on if you want your variable to be mutable or not.

overwitting the XMLHttpRequest causes the load failure

I am trying to count the number of ajax calls. I want to do this to wait until all the ajax calls return.
I have written the following code:
var xmlreqc=XMLHttpRequest;
XMLHttpRequest = function() {
this.xhr = new xmlreqc();
return this;
};
XMLHttpRequest.prototype.open = function (method, url, async) {
return this.xhr.open(method, url, async); //send it on
};
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
this.xhr.setRequestHeader(header, value);
};
XMLHttpRequest.prototype.getAllResponseHeaders = function() {
console.log( this.xhr.getAllResponseHeaders());
return this.xhr.getAllResponseHeaders();
};
XMLHttpRequest.prototype.send = function(postBody) {
// steal the request
nRemAjax++;
// do the real transmission
var myXHR = this;
this.xhr.onreadystatechange = function() { myXHR.onreadystatechangefunction();};
this.xhr.send(postBody);
};
XMLHttpRequest.prototype.onreadystatechangefunction = function()
{
try {
this.readyState = this.xhr.readyState;
this.responseText = this.xhr.responseText;
console.log(this.xhr.responseText); // this line log json data though
this.responseXML = this.xhr.responseXML;
this.status = this.xhr.status;
this.statusText = this.xhr.statusText;
}
catch(e){
}
if (this.onreadystatechange)
this.onreadystatechange();
//do my logging
if (this.xhr.readyState == 4)
{
nRemAjax--;
// only when done steal the response
consoleLog("I'm finished");
}
};
I have injected above code into the browser.
This works fine for most of the Websites, except for http://demo.opencart.com/index.php?route=account/register.
For some reasons, the Region/state field is not loaded properly on page load.
What I found that the Region/Field is populated with JSON data that has been send as a response from ajax call.
Please note that I am adding this script in the head.

Ajax, why the setInterval function doesn't work?

I just have a json page in localhost and I save the data of this page in a file , I need to save this page every 5 seconds, so I developed this code in ajax , using a page in php with an exec command,I used a setinterval function for the update but my code execute the function getRequest only one time.
Here the html:
<script type="text/javascript">
// handles the click event for link 1, sends the query
function getOutput() {
setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
},3000);
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
</script>
And here the php page:
<?php
exec(" wget http://127.0.0.1:8082/Canvases/Fe0_Cbc1_Calibration/root.json -O provami3.json", $output);
echo 'ok';
?>
I'm new to php , javascript ajax etc and I-m learning it a piece at time, I know that maybe there is an easy way for it using jQuery but for now I'm learning Ajax, so I'd like have an advice for doing it with Ajax.
Thank you all.
Do you have called getOutput() function?I don't see it...
Working example with your code here: http://jsfiddle.net/v9xf1jsw/2/
I've only added this at the end:
getOutput();
Edit:
Working example with getOutput call into a link: http://jsfiddle.net/v9xf1jsw/8/
The JS is fine, see example here counting the loops https://jsfiddle.net/tk9kfdna/1/
<div id="output"></div>
<div id="log"></div>
<script type="text/javascript">
// handles the click event for link 1, sends the query
var times=0;
function getOutput() {
setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
},3000);
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
times++;
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
var log = document.getElementById('log');
log.innerHTML = 'Loop:'+times;
return req;
}
getOutput();
</script>
Assuming here your calling getOutput() somewhere as that was not included in your original question if not it may just be that. Otherwise what may be happening is a response from prova1.php is never being received and so the script appears like it's not working. The default timeout for XMLHttpRequest request is 0 meaning it will run forever unless you specify the timeout.
Try setting a shorter timeout by adding
req.timeout = 2000; // two seconds
Likely there is an issue with prova1.php? does prova1.php run ok when your try it standalone.
1) Return false at the end of the setInterval method, I don't believe this is necessary.
2) Use a global variable to store the setInterval, (this will also give you the option to cancel the setInterval).
var myInterval;
function getOutput() {
myInterval = setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
},3000);
}

IndexedDB open DB request weird behavior

I have an app (questionnaire) that uses indexedDB.
We have one database and several stores in it.
Stores have data already stored in them.
At some point a dashboard html file is loaded. In this file I am calling couple of functions:
function init(){
adjustUsedScreenHeight();
db_init();
setInstitutionInstRow();
loadRecommendations();
loadResultsFromDB();
fillEvaluations();
document.addEventListener("deviceready", onDeviceReady, function(e) {console.log(e);});
}
The init() function is called on body onLoad.
setInstitutionInstRow() looks like these:
function setInstitutionInstRow(localId){
//localId = 10;
if (localId == undefined){
console.log("Localid underfined: ");
//open db, open objectstore;
var request = indexedDB.open("kcapp_db", "1.0");
request.onsuccess = function() {
var db = request.result;
var tx = db.transaction ("LOCALINSTITUTIONS", "readonly");
var store = tx.objectStore("LOCALINSTITUTIONS");
tx.oncomplete = function(){
db.close();
}
tx.onerror = function(){
console.log("Transaction error on setInstInstRow");
}
var cursor = store.openCursor();
cursor.onsuccess= function () {
var match = cursor.result;
console.log ("Retrieved item: " + match.value.instid);
// alert("Added new data");
if (match){
setInstituionInstRow(match.value.instid);
console.log("Got localid: " + math.value.instid);
}
else
console.log("localinsid: it is empty " );
};
cursor.onerror = function () {
console.log("Error: " + item.result.errorCode);
}
}
request.onerror = function () {
console.log("Error: " + request.result.errorCode );
}
request.oncomplete = function (){
console.log("The transaction is done: setInstitutionRow()");
}
request.onupgradeneeded = function (){
console.log("Upgrade needed ...");
}
request.onblocked = function(){
console.log("DB is Blocked ...");
}
} else {
instid = localId;
var now = new Date();
//console.log("["+now.getTime()+"]setInstituionInstRow - instid set to "+localId);
//open db, open objectstore;
var request = indexedDB.open("kcapp_db", "1.0");
request.onsuccess = function() {
var db = this.result;
var tx = db.transaction ("INSTITUTIONS", "readonly");
var store = tx.objectStore("INSTITUTIONS");
var item = store.get(localId);
console.log(item);
item.onsuccess= function () {
console.log ("Retrieved item: ");
if (item.length > 0)
var lInstitution = item.result.value;
kitaDisplayValue = lInstitution.krippe;
};
item.onerror = function () {
console.log("Error: " + item.result.errorCode);
}
}
request.onerror = function () {
console.log("Error: " + request.result.errorCode );
}
}
Now the problem is,
var request = indexedDB.open("kcapp_db", "1.0");
the above request is never getting into any onsuccess, oncomplete, onerror states. I debugged with Chrome tools, it never getting into any above states.
Accordingly I am not getting any data from transactions.
And there are no errors in Chrome console.
And here is the request value from Chrome dev:
From above image the readyState: done , which means it should fire an event (success, error, blocked etc). But it is not going into any of them.
I am looking into it, and still can not figure out why it is not working.
Have to mention that the other functions from init() is behaving the same way.
Looking forward to get some help.
You may be using an invalid version parameter to the open function. Try indexedDB.open('kcapp_db', 1); instead.
Like Josh said, your version parameter should be an integer, not a string.
Your request object can get 4 events in response to the open request: success, error, upgradeneeded, or blocked. Add event listeners for all of those (e.g. request.onblocked = ...) and see which one is getting fired.
I had that problem but only with the "onupgradeneeded" event. I fixed it changing the name of the "open" function. At the begining I had a very long name; I changed it for a short one and start working. I don't know if this is the real problem but it was solved at that moment.
My code:
if (this.isSupported) {
this.openRequest = indexedDB.open("OrdenesMant", 1);
/**
* Creación de la base de datos con tablas y claves primarias
*/
this.openRequest.onupgradeneeded = function(oEvent) {
...
Hope it works for you as well.

Categories

Resources