javascript check if null from json - javascript

Im using the following javascript. it writes fine until it gets to a result which doesn't have a value. in console log it shows this
Uncaught TypeError: Cannot read property 'text' of null
but my script below doesn't seem to work
var checkCaption = photo.caption.text;
if (checkCaption == null) {
caption = 'meh';
} else {
caption = photo.caption.text;
}

In your example, photo.caption is null, so your code breaks on the photo.caption.text call, before the check is done.
var caption;
if(photo.caption != null) { // Covers 'undefined' as well
caption = photo.caption.text;
} else {
caption = "meh";
}

In my case i use the JSON.stringify to check I have received {} (null) response from the REST server:
if (JSON.stringify(response.data)=='{}') {
//the response is null
}
else {
//the response of JSON is not null
}
It works fine for me to check if the response is null or not.

For me the check of length of the json object resolved the issue -
if Object.keys(jsonobj).length == 0){
// JSON object is null
}
else {
// JSON object has data
}

Related

jQuery undefined value for some elements

I have a response in json format and check some value in my Jquery code its working fine if i check
dataObject.deviceType==='mobile'
then it's always working fine but for
dataObject.mobileRedirect
Its always return undefined. Please help if i forgot something.
My json response is
{"successType":11,"notificationMessage":"Sucess message","feed_seourl":"chandoo","deviceType":"mobile","mobileRedirect":"\/mobile\/directories\/#category_id=all&subcategory_id=0&country=India&countryFlag=in.png"}
And jquery is
if(dataObject.successType === 11 && dataObject.deviceType==='mobile') {
var mobileuser = dataObject.mobileRedirect;
if(typeof mobileuser == 'undefined'){
window.location.href = window.location.protocol+"//"+window.location.host;
}else {
window.location.href = window.location.protocol+"//"+window.location.host+dataObject.mobileRedirect;
}
}

jquery ajax request returns undefined

I am trying to have a link perform a really simple, request, but I can't seem to figure out why what I returned is "undefined".
Currently the link does a manual page request, but it's such a simple subscription thing, I want it to not refresh the page (hence the preventDefault). But if the JS doesn't work or it's blocked, the link should do a normal page request (best of both worlds?).
Here is the JS that captures the click on a link
$('#subscribe-link').click(function(e)
{
e.preventDefault();
var type = $(this).data('sub');
$.post('/includes/ajax/subscribe-article.php', { 'type':type },
function(data)
{
alert(data.result);
if (data.result == 'subscribed')
{
alert('subscribe');
}
else if (data.result == 'unsubscribed')
{
alert('unsubscribe');
}
});
});
And here is the PHP that feeds it:
if($_POST && isset($_SESSION['user_id']) && $_SESSION['user_id'] != 0)
{
if (isset($_POST['type']))
{
if ($_POST['type'] == 'subscribe')
{
echo json_encode(array("result" => "subscribed"));
return;
}
if ($_POST['type'] == 'unsubscribe')
{
echo json_encode(array("result" => "unsubscribed"));
return;
}
}
}
Now, I've checked what "data" returns by itself which is this:
{"result":"unsubscribed"}
Which is correct, I'm not sure what I'm missing this time.
As the variable data contains the JSON representation of your expected result, it is plainly a String. Yet you try and access information contained in that string as an object. For this to work, you first need to create an object from the string by decoding the returned JSON:
var myData = JSON.parse(data);
alert(myData.result);
...
You need to parse the result as JSON. IE, data_array=JSON.parse(data);

$.parseJSON(resp); if resp is number it works

I was using this to test if server returned data is json.
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
if (json) {
//
} else {
//
}
But it returns true if resp is a number lik 2 or 3 or... It returns null if resp is 0.
Any ideas how to avoid this false situation?
I'm outputting data using php:
echo 0; //returns null
echo 2; //returns as valid json
It appears, 0 is read as string, and 2 is read as number.
If you're expecting an integer, use parseInt:
try {
val = parseInt(resp, 10);
if(val > 0) /* act accordingly ... */
} catch (error) {
val = null;
}
If you want to know if the "JSON is valid," you can use something akin to the following:
function isValidJSON(string){
try {
$.parseJSON(string);
return true;
}
catch(e){ return false; }
}
I suggest something like:
// source from Angular source
function isJson(data) {
return (/^\s*[\[\{]/.test(data) && /[\}\]]\s*$/.test(data));
};
So...
if (isJson(resp))
json = $.parseJSON(resp);
else
alert ('another response: ' + resp);
Numbers like 2 or 3 are technically valid JSON data. Do you expect an object? See e.g. this SO post for methods of checking if the returned variable is an object.
Basically your workflow would be to try to parse it as JSON, and if it succeeds, check if it's an object/list (depending on what you expect).
Example:
try {
json = $.parseJSON(resp);
return (typeof(json) === "object")
} catch (error) {
json = null;
}

JSON or Jquery error: Uncaught TypeError: Cannot read property 'error' of null

I am trying to make an ajax call using the below jQuery.
But I can see in Chrome, i'm getting uncaught typeerror cannot read property 'error' of null. So this stops the preloader from going away. Any idea why it's doing this?
function appendTeam(){
$.ajax({
url : _path + "/core/ajax.php",
type : 'POST',
data : { f: 'getTeam'},
dataType : 'json',
success : function(data) {
if(data.error){
errorMessage('Error: ' + data.error, data.error, data.error);
return false;
}else{
var count = 0;
$.each(data.team, function(i, c){
// check
if(!$('#'+c)) return true;
var element = $('#'+c);
$('input[name="s'+i+'"]').val(element.attr('id'));
$('.slot.'+(i+1)+'.ui-droppable').append(element);
element.data('prevParent', $('.slot.'+(i+1)+'.ui-droppable'));
count ++;
});
appendStatus(count);
setTimeout(function(){
$('#preloader').fadeOut('fast',function(){
$('#preloader').remove();
popUp('match');
});
}, 2000);
}
}
});
}
There is a mistake in your if operator:
if(data.error)...
You should check it like if(data && data.error)... so if the server returned you null instead of JSON object you won't try to access object's property error.
Also maybe you need to handle this case separately:
if(!data) {
// handle empty response
} else if(data.error) {
// handle error
} else {
// process results
}
Test if data is not null before trying acces his error property
Probably the data object does not contains the property error or it is null;
so instead of this
if(data.error) {
you can check for it in a different way :
if(data && data.hasOwnProperty('error')) {
which is more fail-safe.
i think response is null try to see response in using firebug

does this javascript fire when no result is returned from the database

I have the below code:
$.post('get_as_12', {data:selectedObj.value},function(result) {
alert(result[0]) ;
if(result[0] > 0) {
$('#h12_1').attr('checked','checked');
alert('12-1');
} else {
$('#h12_1').removeAttr('checked');
alert('12-2');
}
});
get_as_12 is a MySQL query.
the alert alert(result[0]) ; is fired correctly when there is a database result. if there however is no result and the returned value is NULL how do I get the alert to still fire. more than this, how do I get the else statement to fire:
$('#h12_1').removeAttr('checked');
Thanks in advance.
UPDATE
$.post('get_as_12', {data:selectedObj.value},function(result) {
alert(result[0]) ;
if(result[0].length > 0) {
$('#h12_1').attr('checked','checked');
} else {
$('#h12_1').removeAttr('checked');
}
});
Perhaps something like this:
$.post('get_as_12', {data:selectedObj.value},function(result) {
if(result != null && result[0] > 0) {
$('#h12_1').attr('checked','checked');
alert('12-1');
} else {
$('#h12_1').removeAttr('checked');
alert('12-2');
}
});
That adds a check that result isn't null or undefined. If you're sure that a defined result will be an array with at least one element in it, that should be fine. Otherwise you need to add a check that result.length > 0
I think you are looking for the length of result[0]
if(result && result[0].length > 0) {.......
I'm assuming that result[0] contains an array with the result of your mysql query. With the length property, you can check whether your result set is empty, therefore it should call your statement else-statement if your query doesn't return results.
I expect when the server returns null response it is not being handled correctly by $.post to process the request.
You can try using $.ajax instead, as this allows for better error handling and processing.
$.ajax({
type: 'POST',
url: 'get_as_12',
data: {
data:selectedObj.value
},
success: function(result){
if(result != null && result[0] > 0) {
$('#h12_1').attr('checked','checked');
alert('12-1');
} else {
$('#h12_1').removeAttr('checked');
alert('12-2');
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
// or use alert to send user a message
}
});
The key things to note here are the success and error handlers. The error is triggered if the response is invalid or none is given by the server.
The code is untested; so changes may be required.

Categories