I am using the following code to check my database for login information and receive it back inside the application but I am having the issue that I cannot parse the JSON information. I have parsed it into an array and when I run the following code the console returns:
I am wondering how do I take this a step further and read the number for "loggedin" and get the "username" also. I have tried replacing myArr with myArr[0].loggedin or even with myArr[0] but then I get a return of undefined.
Anyone any suggestions?
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('loginForm').addEventListener('submit', function() {
var usernameTest = document.getElementById('username').value;
var passwordTest = document.getElementById('username').value;
//alert("username is: " + usernameTest);
//console.log("password is: " + passwordTest);
//alert("test");
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
var myArr = JSON.parse(this.responseText);
chrome.extension.getBackgroundPage().console.log(myArr);
}
};
request.open('GET', 'http://localhost/api/login.php?username='+usernameTest+'&password='+passwordTest);
request.send();
});
});
What worked for me after GaetanoM's comment is:
myArr.UAPlugin[0].loggedin or myArr.UAPlugin[0].username
Related
I'm trying to handle a simple XML file with JS (server-side). So far, with every solution I've tried out, the value shows as "undefined".
I've tried a couple of different approaches, yet I still cannot get past loading the XML file itself and successfully displaying it.
When I've tried to parse it with a DOMParser, the node value is "undefined" (see the present code please).
Another approach I've taken before is to treat it as an XML file without changing it to string beforehand - then I get the '.getElementsByTagName('node')[0]; is not a function' error.
function loadXML(postID){
var xmlhttp = new XMLHttpRequest();
var file = 'logs/queue'+postID+'.xml';
xmlhttp.onreadystatechange = function() {
console.log('[DEBUG]Readystate: '+this.readyState+', status: '+this.status);
if (this.readyState == 4 && this.status ==200) {
myFunction(this);
};
function myFunction(xmlfile) {
var xmlDoc=null;
var data = "";
var parser = new DOMParser();
var user;
xmlDoc = parser.parseFromString(String(xmlfile), "text/xml");
var nodes = xmlDoc.getElementsByTagName("node");
for(i=0; i< nodes.length; i++){
tipper = nodes[i].getAttribute("id");
}
console.log(user)
}
};
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
My only expectation is to obtain the node attribute value of the "node" element.
Instead, I keep getting the "undefined" value as a result.
After two days of struggling with this matter, I finally came up with a working solution.
Therefore, in case somebody was having a problem similar to mine, here goes:
First, I've npm-installed libxmljs. From this point, after quickly checking its wiki page, things went almost silky smooth. The modified code can be analyzed below:
function loadXML(postID){
var xmlhttp = new XMLHttpRequest();
var file = 'file.xml';
xmlhttp.onreadystatechange = function() {
console.log('[DEBUG]Readystate: '+this.readyState+', status: '+this.status);
if (this.readyState == 4 && this.status ==200) {
myFunction(this);
};
}
function myFunction(xmlfile) {
var xmlDoc = libxmljs.parseXml(xmlfile.responseText);
var nodes = xmlDoc.root().childNodes();
var node = nodes[0];
var node_id = xmlDoc.get('//user').attr('id').value();
var uname = xmlDoc.get('//name');
var uamount = xmlDoc.get('//u_amount');
var umessage = xmlDoc.get('//u_message');
console.log('[DEBUG] [id=%s] User: %s. Amount: %s. Message: %s.', node_id, uname.text(), uamount.text(), umessage.text() );
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
};
I intend to print the USD value of ETH from
"https://api.coinmarketcap.com/v1/ticker/ethereum/"
using JavaScript. However, when I include the script
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var time = "<b>Last Updated : " + json["time"]["updated"] + "</b>";
var usdValue = "$" + json["eth"]["price.usd"]["rate"];
document.getElementById("data").innerHTML =
usdValue
}
</script>
in my HTML file, along with other scripts of other Price APIs, the code above returns nothing. What am I doing wrong? I need help please.
Try Something like this
<body>
<div id="data" />
<script type="text/javascript">
var json = new XMLHttpRequest(); // start a new variable to store the JSON in
json.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // if HTTP header 200 - ok
var object = JSON.parse(this.responseText); // set the variable 'object' to whatever we get back, in our case it is an array of 10 different arrays
for(var i=0;i<object.length;i++){ // looping through json
var item = object[i];
if(item["symbol"] === "ETH"){ // finding when symbol is ETH
var usdValue = "$" + item["price_usd"]; // Fetching price_usd value
document.getElementById("data").innerHTML = usdValue;
}
}
}
};
json.open(
"GET", // method
"https://api.coinmarketcap.com/v1/ticker/ethereum/", // url
true // async
); // initialise the request
json.send(); //send request
</script>
</body>
Run the code snippet
According https://api.coinmarketcap.com/v1/ticker/ethereum/, the return value of JSON.parse(this.responseText) will be a json array. So pass json[0] to your parseJson().
The parsed json doesn't have field/property of 'time' or 'eth'. I suggest you use following code to get what you want.
let time = `<b>Last Updated : ${new Date(parseInt(json['last_updated'])).toDateString()}</b>`;
let usdValue = `\$${json['price_usd']}`;
I am very new to JS, trying to create simple page which does next:
takes IP of some server
then sends a get request to this server
parses get response,
adds filtered lines to the table on html page.
I was able to do all the steps through the browser console but when, moving to the JS file with get function for some reason function does not return value.
In below code snip line 6 will print undefined in the console.
Any idea how to return "statuses" from the function getStatus?
Should it be some timeout between line 5 and 6?
Thanks!
$("input[type='text']").keypress(function(event){
if(event.which === 13){
var address = $(this).val();
var urlStat = 'http://'+address+':666/bla?open=stats';
var status = getStatus(urlStat);
console.log(status);
$("input[type='text']").val('');
$('table').append("<tr><th>"+address+"</th><th><ul></ul></th><th></th></tr>");
}
});
function getStatus(url){
var xhr = new XMLHttpRequest;
xhr.open("GET", url);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var regexStatus = /(\w+ state:.*?)</g
var response = xhr.responseText;
var statuses = response.match(regexStatus);
console.log('Inside function getStatus'+statuses);
return statuses;
};
}
};
The problem with your code is that the status is returned after your your request has been sent. That gives a small delay. Because you immediatly ask for the return value of getStatus, you will get undefined.
You could solve this problem with a callback function:
function getStatus(url,callback){
var xhr = new XMLHttpRequest;
xhr.open("GET", url);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var regexStatus = /(\w+ state:.*?)</g
var response = xhr.responseText;
var statuses = response.match(regexStatus);
console.log('Inside function getStatus'+statuses);
if(callback) callback(statuses);
};
}
};
You call the getStatus function with a function, which is called after you got a response from you request.
E.g:
getStatus(url,function(statuses){
console.log(statuses);
});
EDIT
For a better and longer explanation, consider to check out How do I return the response from an asynchronous call?
I'm trying to include an if statement that analyzes the webmethod response which is either true or false. I just want to alert the user the post was successful if the response is true or the post was not successful if the response is false.
I can get the response using xhttp.responseText but I can't figure out how to build that into an if statement inside my javascript below:
//JavaScript that Posts to WebMethod
<script>
function createNewComment() {
var xhttp = new XMLHttpRequest();
var url = "http://localhost:57766/PALWebService.asmx/insertComment"
var a = document.getElementsByName("existingguid")[0].value;
var b = document.getElementsByName("newcomment")[0].value;
var c = 'existingguid=' + a + '&newcomment=' + b;
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.send(c);
}
</script>
I figured it out. After checking that readyState was 4 and status was 200 I simply nested another if statement to check the responseText from the XMLHttpRequest and it was true I called another function and if it was false I notified user the post failed on the webmethod. It may not be perfect, but it works for what I need.
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText = true) {
addComment(b, today, userName);
}
else {
document.getElementsByName("newcomment")[0].value = '';
$("#commentLabel").html("Your comment was not saved in the database. Please try again or contact system admin.");
}
}
};
I have created some little jt code, but it gives me error
function Mind(){
var request = "request";
var reply = "reply";
var words = '';
this.Reply = function(){
if(request == words.nouns[0].noun){
reply = words.nouns[0].noun;
}
else
reply = this.words.nouns[0].noun;
}
this.SetRequest = function(req){
request = req;
}
this.GetReply = function(){
return reply;
}
this.Parse = function(u){
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
return result;
}
this.Construct = function(){
words = this.Parse('mind/words.json');
}}
var mind = new Mind();
mind.Parse('mind/words.json');
and here is my json file
{
"nouns": [
{"noun": "child"},
{"noun": "father"}
]
}
In command live all goes well, but when I run this code, appears error
Uncaught TypeError: Cannot read property 'nouns' of undefined
Mutliple errors. The most fundamental one is that your code ignores that XMLHttpRequest is async, and wont return a value in the same way as "regular" functions. Read about it here: How to make a function wait until a callback has been called using node.js. The TL;DR is that you have to pass in a "callback-function" to your parse-method and "return" your value using that function, instead of using a return-statement. Google for "javascript callbacks" and read a few tutorials if this concept is new to you!
You also have some minor errors, like returning result from Parse, but never actually setting result to anything. Also words is being assigned in multiple places in a way that doesn't really make sense. But both of these things will go away when you solve the sync/async issues.
EDIT:
Essentially the fix looks like this:
this.Parse = function(u, callback){ // this "callback" is new
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
callback(null, words); // we're "returning" the words here
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
// no return statement here!
}
this.Construct = function(){
this.Parse('mind/words.json', function(error, words) {
// here you can use your words!
});
}}