4

I am having problems with a JSON AJAX 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 comes back as:

TypeError:$.parseJSON(...) is null

I have tried various methods to check if there is data within the callback but none seem to work. I am very new to using JSON and is wondering whether I should add a different call back via the php page if there is no data to return, however would like to find out if there is a way to do this via the javascript.

1
  • I have tried various methods to check if there is data Which ones? Commented Mar 15, 2013 at 9:05

3 Answers 3

2

$.ajax with post will return HTML in string format you need something like this!

success:function(html)
{
    if(html)
    {
        try
        {
            html = JSON.parse(html);
            if(html.MenuData)
            {
                // do something interesting
            }
            else
            {
                // failed
            }
        }
        catch(e)
        {
            // failed
        }
    }
    else
    {
        // failed because response is empty
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I don't believe you really need that second check for html's validity, basically, drop the if only to if(html), other than that, this is pretty much it, have an upvote
This gets rid of the error but does not seem to fire the functions within the //do something interesting part. Will have a play with this though. It is filtering the blank return from a populated return - just not firing my bit of code after that so far.
Yeah thasts what else part is about, if you didn't get i.e. html.MenuData because response is wrong, you can play around else part.
Sorted - changed $.each($.parseJSON(html).MenuData,.. to $.each(html.MenuData,... Many Thanks :)
2

Here you can specify dataType to use as json

  $.ajax({
    type: 'POST',
    url: ajaxURL,
     data:data,
    dataType: 'json',
    success: function(data){
        JSON.parse(data);
    }

});

And in server side script you must have to encode data using json_encode function.

Comments

1

While fetching json via ajax, here are a few things to note (incase it catches your issue too)

1) Content-Type Json parsing will work fluently when Content-type: application/json A html fetch (meaning Content-Type: text/html or equivalent) needs manually parsing json as String.

2) Jquery version This shouldn't be a problem since it has subsided since version: 1.5 (you might be using latest one, 1.9) Here is a link to the json related bug: http://bugs.jquery.com/ticket/8108

For json intensive coding, people often use jquery-json (http://code.google.com/p/jquery-json/) which a wrapper over simple jquery. You may want to consider if fix isn't easy.

I hope it answers atleast partially. Thanks..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.