Search code examples
phpsqlajaxerror-messages-for

Display error message when ajax result return null value


I would like to ask how to display error message when null value and 0 value in the ajax result from SQL

{"value":
    {"columns": [["More than 85%",null],["Less than 85%",0]],
    "type":"pie"}
}

else no pop out message shown.

$.ajax({
    type: "POST",
    url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
    dataType: "json", 
    success: function (result) { 
        var chart = c3.generate({
            bindto: '#piepie',
            data: result.value,
            color: { 
                pattern: ['#f35213', '#f1af4c'] 
            },
            pie: { title: "Productivity", }
        });     
    },
    error: function() {
        if ((result == null) && (result == 0)){ 
            alert ('Data are not ready yet!!');  
        } 
        else {
            ('error');
        }
    }   
});

Solution

  • The variable result doesn't exist in the error: function. You need to do that test in the success: function.

    The null and 0 values are deep in the structure, you need to access them properly.

    $.ajax({
        type: "POST",
        url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
        dataType: "json", 
        success: function (result) {
            if (result.value.columns[0][1] == null && result.value.columns[1][1] == 0) {
                alert ('Data are not ready yet!!');
            } else {
                var chart = c3.generate({
                    bindto: '#piepie',
                    data: result.value,
                    color: { 
                        pattern: ['#f35213', '#f1af4c'] 
                    },
                    pie: { title: "Productivity", }
                });
            }
        },
        error: function() {
            alert('error');
        }   
    });