1

I have a function A which loads the data from db if the user has liked the image. I have another function B which loads the count for the total number of likes for the image. Both these functions return response using JSON.

If I call them individually, everything works fine, but if I call function B in function A, I get no JSON response and nothing happens although firebug does show two JSON arrays being outputted.

What is wrong with the code?

Function A:

public function loadLikes() {
        //sql query

            try
            {


                $query = $this->_db->prepare($sql);
        $params = array(':imageid' => $imageid, ':author' => $author);
        $query->execute($params); 

                //calling function B
                $this->countLikes($imageid);

                if ($query->rowCount() > 0) {

                    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
                    if ($row['like'] == '1') {
                        $response = json_encode(array('like' => true));
                        echo $response;
                        return TRUE;
                    }
                    elseif ($row['like'] == '2')  {
                        $response = json_encode(array('unlike' => true));
                        echo $response;
                        return TRUE;
                    }
                    else {
                        $error = "Invalid";
                        $response = json_encode(array('like' => false, 'text' => $error));
                        echo $response;
                        return FALSE;
                    }
                  }

                }
                else {

                    $response = json_encode(array('unlike' => true));
                    echo $response;
                    return FALSE;
                }

            }
            catch(PDOException $ex)
            {
                echo json_encode(array('like' => false, 'text' => $ex));
                return FALSE;
            }

    }

Function B:

public function countLikes($i) {
        //sql query

            try
            {           
                $query = $this->_db->prepare($sql);
                $params = array(':imageid' => $i);
                $query->execute($params); 

                if ($query->rowCount() > 0) {
                    $count = $query->fetchColumn();
                    $response = json_encode(array('count' => $count));
                    echo $response;
                    return TRUE;
                }


            }
            catch(PDOException $ex)
            {

                return FALSE;
            }

    }

jQuery:

$.ajax({
                            type: "POST",
                            url: url,
                            data: postData, 
                            dataType: "json",
                            success: function(data){
                                $(".count-like").show(600).text(data.count);
                                if(data.like) {
                                    $("a#alike").attr('class', 'starred');  
                                }
                                else if (data.unlike) {
                                    $("a#alike").attr('class', 'unlike');
                                }
                                else {
                                    alert(data.text);
                                }
                            }
                        });

1 Answer 1

1

If you invoke both functions, then each will output a JSON array. This will result in a HTTP response with following content:

{"like":1}{"count":2}

Both arrays would be valid separately. But if concatenated like this, it's no longer valid JSON.

Instead of outputting the json serialization with echo you should collect it in a temporary variable, merge the two arrays, and then output the combined array with a single:

echo json_encode(array_merge($countArray, $likeArray));

Example adaptions of your code

Function B should become:

public function countLikes($i) {
    //sql query

        try
        {           
            $query = $this->_db->prepare($sql);
            $params = array(':imageid' => $i);
            $query->execute($params); 

            if ($query->rowCount() > 0) {
                $count = $query->fetchColumn();

                /* JUST RETURN HERE */
                return (array('count' => $count));
            }


        }
        catch(PDOException $ex)
        {

            /* INSTEAD OF FALSE use an empty array,
               which is interpreted as false in boolean context*/
            return array();
        }

}

Then when you call the function:

//calling function B
$countArray = $this->countLikes($imageid);

This will always be an array. Which you then can use in the output code:

$response = json_encode(array('like' => true) + $countArray);

(It's still inadvisable to have an echo right there. But too much code, too little context to propose a nicer rewrite. And if it works, ..)

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your response. How would I return the result from function B to A though? I tried in function A: if ($this->countLikes($imageid)==TRUE): $count = json_encode(array('count' => $count)); endif; which throws the error: Undefined variable count.
In countLikes replace the $response = json_encode(..); with just return array(...); and remove the echo ... and return TRUE; instead. When calling it from the other function, use $countArray = $this->countLikes(...); and forget about the TRUE result. (If you need the TRUE test elsewhere, you have to design a separate wrapper function.)
Okay, I am sure I'm doing something stupid here, but this is what I did: (Function B) if ($query->rowCount() > 0) { $count = $query->fetchColumn(); return json_encode(array('count' => $count)); } (Function A): $count = $this->countLikes($imageid); .... $like = json_encode(array('like' => true)); $response = json_encode(array_merge($count, $like)); echo $response; and this is throwing the error: Warning: array_merge(): Argument #1 is not an array
on top of this your using PHP5 and classes (the public declaration told me), you should not echo from a method unless its die function or (due to error), you should allways return the data then the page calling it should then handle the data for outputting, the only time this is broken for better is MVC then your models never echo they return
@fuz3d: Code in comments is not that useful. See answer update. Your error was trying to merge the json_encode string result with another array. There can only be one json_encode, and the arrays have to be merged before that.
|

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.