0

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;
            })
        })

I have took the advise and used JResponseJson

$db->setQuery($query);
$db->execute();
$marks = plgContentLikesHelper::getMarks($articleID);
$data=array();
$data['likes'] = $marks->likes;
$data['dislikes'] = $marks->dislikes;
//echo json_encode($data);
echo new JResponseJson($data);

The response has changed but mistake still be present.

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

{"success":true,"message":null,"messages":null,"data":{"likes":"6","dislikes":"0"}}{"success":true,"message":null,"messages":null,"data":[]}

Can you help me find where I'm wrong?

2
  • Please extend your question here with the information from your stackoverflow question and with your json controller code. You have already errors in your code there. Commented Nov 13, 2017 at 10:05
  • @Pavlo are we able to progress this abandoned page? Commented Jun 28, 2020 at 1:28

2 Answers 2

1

The answer is in the next simple code:

die();

$data=array();
$data['likes'] = $marks->likes;
$data['dislikes'] = $marks->dislikes;
echo json_encode($data);
die();

But in Joomla documentation that moment isn't shown.

1
  • He can use "exit;" as well :D
    – troyKoutei
    Commented Feb 12, 2018 at 8:10
0

First, what is the json parsing error telling you...

{"success":true,"message":null,"messages":null,"data":{"likes":"6","dislikes":"0"}}{"success":true,"message":null,"messages":null,"data":[]}
//                                           this is the expected end of string --^

What you have are two separate json strings which have been concatenated (with no glue) to form a single string because you have one echo followed by another echo -- this will never parse. Using die() or exit() is not a graceful solution for halting an unknown loop (unknown to us because it is not posted in the question).

It would be a greater service to you and your future projects to isolate why your code is performing two iterations of echo new JResponseJson($data);. I don't see anything strange about your jquery, so I'll assume the issue is isolated to your function call within your helper class. If you show more, we can help more.

You can plainly see that the first pass is receiving the likes and dislikes data:

{"success":true,"message":null,"messages":null,"data":{"likes":"6","dislikes":"0"}}

and the second pass is not:

{"success":true,"message":null,"messages":null,"data":[]}

As an aside, I'll mention that you don't need this line of code: $data=array();. You are hardcoding the keys so the empty declaration adds no benefit. What I will say is, it would be wise to add a try{}catch{} block in case you encounter a syntax or logic failure in your query.

To bake together my advice, your code could be written something like this:

$db = JFactory::getDbo();
try {
    $query = $db->getQuery(true)
              //->update()... or insert() or whatever...
    $db->setQuery($query);
    $db->execute();
    $data['message'] = !$db->getAffectedRows()
        ? "Logic Error - No Affected Rows"
        : "Query Successful";
} catch (Exception $e) {
    $data['message'] = "Syntax Error - No Affected Rows"; // . $e->getMessage();
}

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

echo new JResponseJson($data);  // this should occur just once and optimally at the end of your function block

As for your core issue, you will either need to find and eliminate the loop in your function or if you actually want to send multiple sets of success, message, messages, and data as the ajax response, then you will need to merge your arrays before converting to json.

My #1 suspicion is that the getMarks() method contains a line of code which echoes a json string. If you are unable to remove/comment this line, then you will need to engage "output buffer" handling to silence the method when you call it.

1
  • @PavloN if you post more of your code, please ping me (leave a comment containing @mickmackusa) so that I can see what's new. Commented Jun 7, 2018 at 0:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.