user2997418 user2997418 - 2 months ago 20
jQuery Question

Display message when AJAX return empty data

I have a simple AJAX code that fetch data from DB and display it in a DIV, I want to display an error message when no data found:

$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
data: $("#searchForm").serialize(), //add the data to the form
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
if(data.trim()==''){alert("Nothing Found");} //DOESN't WORK
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});

}
});

Answer

What you try to check is empty spaces , not the empty data. You can use error handle;

$.ajax({
type: 'POST',
url: 'models/fetchUsers.php',       //the script to call to get data
data: $("#searchForm").serialize(), //add the data to the form
dataType: 'json',                   //data format
error: alert("Nothing Found"),      //error message when data is empty
success: function(data)             //on recieve of reply
    {
        $.each($(data), function(key, value) {
        $('#itemContainer').append(value.user_id);
                });

    },
error: function()
    {
       alert("no data");
    }

});
Comments