Search code examples
ajaxjoomlasyntax-errorresponse

Joomla JSON.parse: unexpected non-whitespace character after JSON data


I want to use jQuery.ajax for sending new mark(about article) to database and changind number of marks on page. But I receive bad AJAX response from server.

{"likes":"40","dislikes":"29"}{"success":true,"message":null,"messages":null,"data":[]}

and error:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 31 of the JSON data

It seems there must not be the second ajax response. But I'm not understand where it have taken.

That is my php code from Joomla plugin.

$marks = plgContentLikesHelper::getMarks($articleID);
        $data=array();
        $data['likes'] = $marks->likes;
        $data['dislikes'] = $marks->dislikes;
        echo json_encode($data);

That is my jQuery code from Joomla plugin.

jQuery(document).ready(function(){

            jQuery('div.plg-likes > a ').click(function (e) {
                var id = jQuery(this).parent('div.plg-likes').attr('id');
                var opinion = jQuery(this).attr('id');

                jQuery.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "index.php?option=com_ajax&group=content&plugin=likes&format=json",
                    data: { articleId: id, articleOpinion: opinion },
                    success: function(data){  /* troubles are here */
                            alert(data["likes"]);
                    }
                })
                return false;
            })
        })

Solution

  • SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 31 of the JSON data

    The error is pretty self explanatory, you have an error in your JSON structure at column 31. Your JSON as provided in the question is:

    {"likes":"40","dislikes":"29"}{"success":true,"message":null,"messages":null,"data":[]}

    So, {} denote objects and your string has two JSON objects in a row. Have a look at json.org to understand your JSON.

    Column 30, is where your object is ending, and there appears to be a second object being added… you don't specify the version of Joomla so as JSON handling varies amongst all the different versions you will need to read the Joomla docs on the way JSON is handled for the version you're using.

    My guess is that Joomla (which I haven't used for over a year) is adding some default attributes to in it's standard JSON response (which indicates you're using a relatively recent 3.x version).

    I would suggest that you:

    1. try asking on the Joomla Q&A site
    2. try to die() (or something similar) after your echo json_encode($data); line rather than letting Joomla handing the end of execution
    3. have a look at JResponseJson if your version has it.