I am having problems with an AJAX JSON callback when the returned JSON object contains no data. My code is as follows:
$.ajax({ type: "POST", url: "includes/get_menu_name.php", headers: {"cache-control": "no-cache"}, data: data, success: function(html) { //alert(html); var app_data = ""; if (html.MenuData != 0) { $.each( $.parseJSON(html).MenuData, function() { app_data += "<li data-short='"+this['dish_short']+"' data-desc='"+this['dish_desc']+"' data-dish_id='"+this['dish_id']+"'>"+this['dish_name']+"</li>"; }); $('.listbox').show(); $('.nameslist').html(app_data); $('li').hover(function() { $(this).addClass('hover2'); },function(){ $(this).removeClass('hover2'); }); if (html == "") { $('.listbox').hide(); } $('li').click(function() { //alert($('li', this).data('short')); $('.price').val(""); var main_name = $(this, 'li').text(); $('.main_name').val(main_name); //$('.price').val($(this).find('.ajaxid').text()); if(main_name.length > 40) { $('.short_name').val($(this).data('short')) } else { $('.short_name').val(main_name); } if($(this).data('desc')!="") { $('.dish_desc').val($(this).data('desc')); } var dish_id=$(this).data('dish_id'); $('.main_name').data('dish_id', dish_id); $('.listbox').hide(); }); } } });//end ajax
The error is returned as:
TypeError:$.parseJSON(...) is null
I tried various methods to check if there is data in the callback, but nobody is working. I am very new to using JSON and wondering if I should add another callback via php page if there is no data to return, however I would like to know if there is a way to do this with javascript.
source share