jquery check if json var exist - javascript

How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?
function myPush(){
$.getJSON("client.php?action=listen",function(d){
d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
$('#display').prepend(d.chat_msg+'<br />');
if(d.failed != 'true'){ myPush(); }
});
}
Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.

You don't need jQuery for this, just JavaScript. You can do it a few ways:
typeof d.failed- returns the type ('undefined', 'Number', etc)
d.hasOwnProperty('failed')- just in case it's inherited
'failed' in d- check if it was ever set (even to undefined)
You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.
Reference:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

Found this yesterday. CSS like selectors for JSON
http://jsonselect.org/

You can use a javascript idiom for if-statements like this:
if (d.failed) {
// code in here will execute if not undefined or null
}
Simple as that. In your case it should be:
if (d.failed && d.failed != 'true') {
myPush();
}
Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.

Related

How to use localStorage in JavaScript to keep track of a true/false variable? [duplicate]

I noticed that I cannot set boolean values in localStorage?
localStorage.setItem("item1", true);
alert(localStorage.getItem("item1") + " | " + (localStorage.getItem("item1") == true));
Always alerts true | false when I try to test localStorage.getItem("item1") == "true" it alerts true ... How can I set an item in localStorage to true?
Even if it's a string, I thought only === would check the type?
So
alert("true" == true); // should be true?
For the moment, all the implementations Safari, WebKit, Chrome, Firefox and IE, are following the current version of the WebStorage standard, where the value of the storage items can be only a string.
An option would be to use JSON parse and stringify method to serialize and deserialize the data, as I suggested some time ago in another question, for example:
var value = "true";
console.log(JSON.parse(value) === true); // true
Firefox's implementation of Storage can only store strings, but on 2009 September, W3C modified the draft to accept any data. The implementation (still) isn't caught up yet (see Edit below).
So in your case the boolean is converted to a string.
As for why "true" != true, as written in the description of Equal (==) in MDC*:
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
Note that the string is converted to a Number instead of a Boolean. Since "true" converted to a number is NaN, it will not be equal to anything, so false is returned.
(*: For the actual standard, see ECMA-262 §11.9.3 “The Abstract Equality Comparison Algorithm”)
Edit: The setItem interface was reverted to accept strings only on the 2011 Sept 1st draft to match the behavior of existing implementations, as none of the vendors are interested in supporting storing non-strings. See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 for detail.
My solutions:
function tytPreGetBool(pre) {
return localStorage.getItem(pre) === 'true';
}
This is related to CMS’s answer.
Here’s a little function I’ve been using to handle the parsing part of this issue (the function will keep doing the Right Thing after the browser implementations catch up with the spec, so no need to remember to change out code later):
function parse(type) {
return typeof type == 'string' ? JSON.parse(type) : type;
}
I'd like to point out that it might be kinda easier just to wrap plain boolean value inside object and then, using JSON.stringify create local storage content and other way around, JSON.parse to retrive it:
let storeMe = {
myBool: true
}
localStorage.setItem('test', JSON.stringify(storeMe))
let result = JSON.parse(localStorage.getItem('test'))
Use store.js:
localStorage.setItem('isUser', true)
localStorage.getItem('isUser') === "true" //true
npm i -D store
↓
store.get('isUser') //true
What I usually do is just save the value in LocalStore as a Boolean, and then retrieve with a parsing method, just to be sure for all browsers. My method below is customized for my business logic. Sometimes I might store smth as 'no' and still need false in return
function toBoolean(str) {
if (typeof str === 'undefined' || str === null) {
return false;
} else if (typeof str === 'string') {
switch (str.toLowerCase()) {
case 'false':
case 'no':
case '0':
case "":
return false;
default:
return true;
}
} else if (typeof str === 'number') {
return str !== 0
}
else {return true;}
}
I'm not sure if LocalStorage can save boolean values but I can tell you that when you do alert("true" == true); it will never evaluate to true because you are implicitly comparing a string to a boolean. That is why to set boolean values you use true instead of "true".
eval can also be used carefully under some cases.
console.log(eval("true") === true) //true
When I need to store a flag I usually do:
localStorage.f_active = true (stored value is 'true' and it's fine)
if localStorage.f_active — passes
and to unflag:
delete localStorage.f_active
if localStorage.f_active — doesn't pass (returned value is undefined)

How can avoid !! comparation in JavaScript?

I am using this "!!" comparation in order to compare with "undefined". However, is there any other way to do it?
isWidgetTemplatesLoaded: function(widgetName) {
return !!templates[widgetName];
}
Thanks
You could use typeof to check for undefined:
(typeof templates[widgetName] !== 'undefined')
typeof always returns a string. It returns "undefined" if the value of the variable is undefined or the variable does not exist.
You can use the typeof operator
typeof templates[widgetName];
else you can also use like this
if (templates[widgetName] === undefined) {
// rest of code
}
else {
// rest of code
}
To check for undefined you can just use the no-conversion equal/different operators:
if (x !== undefined) { ... }
if (y === undefined) { ... }
note however that this doesn't have the exact same meaning of !!. The double-negation for example returns true even for false, null, 0 or "" despite the fact that these values are not undefined.
By the way in Javascript you should basically always use === and !== instead of == and !=, unless you really need the crazy implicit conversion that equality/different operators do (and no one needs that). Good Javascript editors will warn you about any use of == or != as they are just bug-hiding places.
In the specific of your question code the !! logic seems wrong on a philosophical level because an empty template could be "" and this function would say that the template has not been loaded while instead it has been loaded and simply happens to be the empty string.
You could use the in operator, if you know, if the property exist with some value, other than undefined.
return widgetName in templates;

outputting content based on whether variable object equals "true"

I thought this would be straight forward after reading through w3c tutorials etc! But I appear to have something incorrect as the code doesn't output anything!
The variable is set based on whether the user is logged in or not:
var theJSON={"LOGGEDIN":false};
var theJSON={"LOGGEDIN":true};
I am then trying to show on the front end whether the user is logged in or not:
$(document).ready(function() {
if (typeof(theJSON[LOGGEDIN]) == true ) {
document.write ("Logged in")
} else {
document.write ("Not logged in");
}
i must be missing/mistyping something so simple?
There a couple of things wrong in your code:
When you try to access the LOGGEDIN property of the object, you are missing quotation marks. The expression theJSON[LOGGEDIN] will first try to get the value of the variable LOGGEDIN to use its value as property name. If such a variable does not exist (like it is in your example), the code will throw an error.
Now, The value of theJSON['LOGGEDIN'] is true and the type of the value is a boolean. typeof(theJSON['LOGGEDIN']) == true will never be true, because the typeof operator returns a string with the name of the data type, i.e. typeof(theJSON['LOGGEDIN]') will return "boolean".
If you just want to test whether the value is true, do:
if (theJSON['LOGGEDIN'])
w3schools is really not the best site to start learning about JavaScript, have a look at http://eloquentjavascript.net/ and the MDN JavaScript Guide instead.
if (typeof(theJSON["LOGGEDIN]") == true )
or
if (typeof(theJSON.LOGGEDIN) == true )
BTW, better use === instead of ==
if the value is number 1 it will still pass the condition.
Firstly, your theJSON is an actual object as given, not a JSON string. If it was you'd need to parse it as suggested.
The expression theJSON[LOGGEDIN] is incorrect syntax, you can either say theJSON.LOGGEDIN or theJSON["LOGGEDIN"]. And as this is a boolean, typeof(theJSON.LOGGEDIN) == "boolean".
The expression is a boolean, but it's value is true, so you can just write if (theJSON.LOGGEDIN).

does ""===null?

when comparing string to see if it is empty, is there any difference between:
if($string==NULL){
//do work
}
and
if($string==""){
/do work
}
Just wondering beacuse I want to know which one is more effective in detecting blank input.
You're kind of asking several vaguely-related questions here. PHP and JavaScript aren't the same language, and you're referencing different operators in the question title and body. In any event:
PHP:
'' == null true
'' === null false
JavaScript:
'' == null false
'' === null false
You might want to consider these tests for general "did I get something in this string variable":
PHP:
if(!empty($string)) {
// do work
}
JavaScript:
if($string) {
// do work
}
Yes, there is a difference. Checking if $string==Null will actually check to see if the variable has been initialized at all, and $string=="" looks to see that the string actually exists, but that it just holds a 0-length string
To test in PHP:
<?php echo var_dump("" === NULL); ?>
To test in JavaScript:
console.log("" === null)
Both produce false, so you can't do that in either language.
Even if it worked, it is not obvious what you mean by comparing with null; this isn't C where it's constantly used for missing values. If you're going to get a string as input, comparing to the empty string is more clear.
I`am using empty() function in PHP. It is not depends on type of the variable. However, when comparing with "==" (not "==="!), NULL becomes empty string ("") when comparing to string.
does “”===null?
No.
Behold the power of testing... for javascript anyway.
alert("" === null);
In JavaScript, the answer is no. An empty string does not equal null, though both are falsey values.
Check the manual, "" is not identical to null because the former is a string and the latter is null, and === checks for equal types as well as equal values.
Take a look at this: http://php.net/manual/en/language.operators.comparison.php

checking for invalid javascript function parameters

If i need to check a parameter i do this.
if ((typeof param == 'undefined') || (param == null)){
param = ''; //or param = false;
}
And if it's meant to be a number i might throw in a isNaN check too. I was just wondering if there were any other things i should check for or what you do if you need to check your parameters. I know javascript has a lot of quirks that could affect something like this. What is good practice to check for?
Thanks
Any object evaluates to false in a boolean expression if it is false, undefined, null, NaN, 0, "0", "false", or "" (the empty string).
To check for all of these at once concisely, you can just do it like this:
if(!param)
I would simply pull a cliché and say that "it depends on what you want to do"..
If you just want to make sure the value is defined and sent to the function, the code you used should be fine.
You can of course also check for elements within the arguments array, like
if (typeof arguments[0] != "string") {
alert("Has to be string");
}
// or even
if (arguments.length < 1) {
// there aren't any parameters
}
etc...
the arguments array is very helpful in many ways. You can also use it to overload functions - to provide different functionality or arguments depending on the number of arguments provided, etc..
But other than that, I don't know what you need.

Categories