Test if data from array has value Javascript - javascript

I want to test if the data array in the code below has content, because when a user gives a packageid (variable in the code below) that doesn't exist i want the else from the "if...else" to be executed. When i put in a packageid that exists everything works fine, but when i put in no number or a number that doesn't exist, the else side does't get evaluated.
function getInfoAndStatus(){
sym.$("customer_name").empty();
packageid = $("#tracknrfield").val();
var url = "http://student.howest.be/sylvain.vansteelandt/fedex/server/getPackageTracking.php?id=" + packageid;
$.getJSON(url,function(data){
if(data && data[0].id){
$("<span />", {
text: "Customer name: " + data[0].customer_name + " " + data[0].customer_firstname
}).appendTo(sym.$("customer_name"));
} else {
$("<span />", {
text: "The package with number " + packageid + " has not been found. Please try again."
}).appendTo(sym.$("customer_name"));
}
});
}
getInfoAndStatus();

Check your javacript console for any errors. data may be null or an empty array.
Adding a check for console.log(typeof data) may be useful as well.
Sight unseen, I'd most likely do something like if (data && data.length > 0)

If you check your console output, I'm betting you'll see an error there.
Your if check should look like:
if(data && data[0] && data[0].id)
As you may not have an element in your array.

Related

Unable to parse valid json file

Logic
I've a JSON file as follows:
[
{
"title":"Article Title 1",
"url":"https://mywebsite.com/articles/article1.html",
"type":"codes"
},
{
"title":"Article Title 2",
"url":"https://mywebsite.com/articles/article2.html",
"type":"games"
},
{
"title":"Article Title 3",
"url":"https://mywebsite.com/articles/article3.html",
"type":"codes"
}
]
And I'm reading this file, then populating my html page for each item in the file (so there are 3 titles, means 3 containers on my page).
Problem
There was no error before, but now I get an error in console: *SyntaxError: JSON.parse: expected ',' or ']' after array element at line 12 column 2 of the JSON data*
BUT, it all works if there are only 2 articles! After adding the third dataset, there is error. The file format seems correct, there is "," at the right places, I converted it in different encodings but same error.
Code
Main Request:
I'm requesting JSON file on document load like this:
$(document).ready(function(){
var reqdata = new XMLHttpRequest();
reqdata.open('GET', "https://website.com/dat/data.json");
reqdata.onload = function() {
if (reqdata.status >= 200 && reqdata.status < 400) {
try{
var postData = JSON.parse(reqdata.responseText);
render_posts(postData); // this creates dynamic content in html
//console.log(postData);
} catch (err) {
alert(" JSON Parse Error :'( ")
}
} else { alert("JSON Requestion Server Error!") }
}; reqdata.onerror = function() { alert("JSON Request Connection Error!") };
reqdata.send();
});
Populating HTML:
This is called from the code above if JSON.parse is working. This part works fine, just for reference..
function render_posts(data) {
var htmldata = ""; var cardId = "";
for (var x = 0; x < data.length; x++) {
cardId = "card-type-" + data[x].type;
htmldata += "<div class='card' id='" + cardId + "' onclick='card_clicker(\"" + data[x].url + "\")'><div class='header'>" + data[x].title + "</div><div class='decor'></div></div>";
}
cardWrapper.insertAdjacentHTML('beforeend', htmldata);
}
Help: Any help is appreciated.. Can't figure out what's the real problem. The JSON file looks fine. I tried formatting it online, but same results. I'm quite new to AJAX. Tried other solutions on stackoverflow but still the same..
It's a small url decoding problem with JSON decode. Instead of adding the url like:
"url":"https://mywebsite.com/articles/article2.html"
It has to be given escape character backslash like this:
"url":"https:\/\/mywebsite.com\/articles\/article2.html"
And now everything is working fine!
Probably hard to notice extra characters somewhere
or
non-standard double quotes used
or
some other character that is not as you think it is (comma?)

Checking for null only gets "Cannot read property '1' of null" in nodejs

I am trying to test for a null value after a # in a string. I have tried it various ways but I always get a Cannot read property '1' of null when submitting test data. I have ferreted out the errors I can think of but this one I cannot seem to get around. Please keep in mind I am a beginner at this, I haven't programmed since cobol days and the last time i worked on javascript was in the early 2000s.
//start test data, 5 possible strings that may pass through
elt.message = '#1a' //goes through the script good
elt.message = '#12b' // goes through
elt.message = '#123c' //goes through
elt.message = '' //is ignored
elt.message = '# ' //crashes server
//end test data
//First lets test to see if # is in the message. If true then we will parse it and add it to the database.
var str = elt.message;
var substr = '#';
var vtest = str.indexOf(substr) > -1;
if (vtest == 1){
var Vname = elt.author;
console.log('We tested for # and the value is true');
//extracts the number and the letter after the # from incoming chat messages
var test = elt.message; // replace with message text variable.
var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);
if (pstr) {
var numbers = pstr[1];
var character = pstr[2];
var chupp = character.toUpperCase(); //Converts the lowercase to uppercase
}
//Tests to see if neither the question number or the possible answer is left out
//if (pstr[1] !== '' && pstr[2] !== ''){ //doesn't work =(
if (pstr[1] !== null && pstr[2] !== null){ //doesn't work either =(
console.log('we processed the numbers after the #sign and assigned the numbers and letter into variables.')
console.log('The question number is: ' + pstr[1]);
console.log('The letter processed is: ' + pstr[2]);
// Grabs the date and converts it into the YYYYMMDD string.
var dobj = new Date();
var dstr = dobj.toString();
var dsplit = dstr.split(' ');
let currentdate = `${dobj.getMonth() < '9' ? `0${dobj.getMonth() + 1}` :
dobj.getMonth() + 1}`;
currentdate = `${dsplit[3]}${currentdate}${dsplit[2]}`;
console.log(currentdate)//remove when done
//checks to see what the highest question number is in the database
var sel = con.query("SELECT * FROM questions WHERE ClassID = "+ currentdate + " ORDER BY QuesID DESC LIMIT 1", function (err, result){
if (err) throw err;
console.log('Total number of question records: '+result[0].QuesID);
console.log('the script is querying with' + pstr[1]);
console.log('the scripts answer letter is ' + pstr[2]);
if (pstr[2] != '' && pstr[1] <= result[0].QuesID ){
var query = con.query("SELECT * FROM questions WHERE ClassID = " + currentdate + " AND QuesID = " + pstr[1], function (err, result) { // Selects the record based on the Date and the question number variables provided above
if (err) throw err;
console.log('it got past the test')
if (result[0].AnsweredFirst === '' && result[0].AnswerLetter === chupp) { //Test to see if the AnsweredFirst is empty and that the Answer letter matchs with whats on file
console.log('MATCH!');//remove when done
var sql = "UPDATE questions SET AnsweredFirst = '"+ Vname + "' WHERE ClassID = " + currentdate + " AND QuesID = " + pstr[1]; //Updates the record with the first person who answered the question in the AnsweredFirst field
con.query(sql, function (err, result) {
if (err) throw err;
console.log(Vname + " answered question " + pstr[1] + " First!");
});
}
});
}
});
} else {
console.log('Either the question number or the letter was left blank so we are skipping'); //the viewer did not put in a proper number and letter after the # sign
}
} else {
console.log('No signs of # so skipping queries') //if there is no # sign the message is not processed
};
I added the rest of the script to get a better idea. Messages are passed to the server from a chat client.
I'll give it a try moving the block of code into the first if statement. I know its messy but honestly i am surprised I got this far.
var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);
means that if no match is found for your regex, then pstr is null
in that case any index of pstr (like pstr[1], pstr[2]) will throw the error you described:
Cannot read property 'n' of null
Solution:
Before using indexes, check if the variable has a value or not
if(pstr !== null) {
// do something with pstr[1]
}
Edit:
And as nnnnnn rightly pointed out, you cannot explicitly store a null value in a string.
Look. If your test string did not match your regular expression then pstr assigned to null. Besides in next if condition you tried to check first element of pstr without checking it on null value:
if (pstr[1] !== null && pstr[2] !== null){ //doesnt work either =(
So, I think you need either add pstr!==null in second if or move all condition branch from this if inside then part of previous one if statement.

"Try...Catch" Block not Working with parseInt()

What I'm trying to do:
I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
The above code works just fine, and does exactly what I want it to do for the scope of my program.
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
What I'm trying to accomplish with the try...catch block is simply to make sure that
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
are actually numbers.
The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!
Also: I looked at both of these links and was unable to understand my problem.
javascript parseInt return NaN for empty string
http://www.w3schools.com/jsref/jsref_isnan.asp
Your root problem here is that isNaN() tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.
You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()
It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And, then there's no reason to use exceptions in your code, so you can just do this:
if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
alert("Error! You must enter a number into the qty and cost fields!");
}
Also, in your code, some .Value properties look like maybe they should be .value (lowercase).
In your first code block
var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);
You are using Value, which should be value, that's case-sensitive.
By the way, isNaN returns boolean, you don't have to compare with true

Writing onto HTML page

So for a brief context, my program reads in a file and displays it onto the html page. The code below uses a regex expression to read that file and extract the errors. Instead of using console.log each time and debugging, is there any I way I could just write the results onto the HTML page?
When I used:
document.getElementById("").innerHTML
it would just print out the last summary instead of printing out all of the summaries.
I tried using a controller and ng-repeat (AngularJS) to do it, but somehow I did not do it right.
Any ideas -- doesn't have to be in AngularJS???
while ((match = reDiaBtoa.exec(reader.result)) != null) {
if (match.index === reDiaBtoa.lastIndex) {
reDiaBtoa.lastIndex++;
}
// View your result using the match-variable.
// eg match[0] etc.
// extracts the status code: ERROR
if (match[2] === "ERROR" || match[2] === "FATAL" || match[2] === "SEVERE") {
console.log("Time: " + match[1]);
console.log("Thread Name: " + match[3]);
console.log("Source name & line number: " + match[4]);
console.log("Log Message: " + match[5] + '\n');
console.log("-----------------------------------------------------------------");
}
} //end of the while loop ((match = reDiaBtoa.exec.....))
If you use
document.getElementById("someId").innerHTML =
it'll overwrite the existing html.
instead, use
document.getElementById("someId").innerHTML +=
Create a string variable before your while loop and then append to it in your loop:
var outputToDisplay = "";
//While loop
outputToDisplay += "Time: " + match[1];
//etc
//End While
document.getElementById(theId).innherHTML = outputToDisplay;

Javascript (and JSP) won't create table properly with if statement

So i'm using multiple if statements to draw data from a database based on the users search criteria.
What i'm struggling with is
if(request.getParameter("searchProperty")!= ""){
SearchStatement = "town_city = '" + request.getParameter("searchProperty") + "'";
if(request.getParameter("bedrooms") != "0"){
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'";
}
}
with the idea that this concatenates a string to use as a query in the database, and bring back the results the user is searching for (this is a property searching website). I thought i'd done the if statement correctly. From what i understand, from what i've put, if the user were to select 0 in bedrooms it should return ALL results, but instead it returns NONE (who wants a house without a bedroom..) Can somebody explain what's going wrong please?
here's where the SQL statement is built and input
MyProperties = bookSQL.executeQuery("SELECT * FROM PROPERTIES WHERE " + SearchStatement);
with the expected outcome being, for example
SELECT * FROM PROPERTIES WHERE Location = 'input' AND Bedrooms = 'value'
unless value = 0 where it should just be
SELECT * FROM PROPERTIES WHERE Location = 'input'
i think the problem is with this statement,
request.getParameter("bedrooms") != "0"
should be something like this ,
(!request.getParameter("bedrooms").isEmpty())
Remember you are comparing the strings
so if is "0"
if(request.getParameter("bedrooms").equals("0")){
return SearchStatement ;
}
else {
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'"
}
Hope this helps!!

Categories

Resources