mercredi 1 juillet 2015

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data - tried to parse a php if/else statment

I am building a search which will list a number of users and I am getting this error when I am trying to load more pages to show more users in Chrome dev tool:

Uncaught SyntaxError: Unexpected token <

But I am getting this error in firebug which I think is more conclusive:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

var result = JSON.parse(res);

Here is my ajax function in my index.volt

function(cb){
        $.ajax({
            url: '/search/search?q=' + mapObject.q + '&sort=<?php echo $sort;?>' +  '&page=' + mapObject.page,
            data:{},
            success: function(res) {
                var result = JSON.parse(res);
                if (!result.status){
                    return cb(null, result.list);
                }else{
                    return cb(null, []);
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                cb(null, []);
             }
    });

And here is my searchAction() in my Controller:

public function searchAction()
    {
        $q = $this->request->get("q");
        $sort = $this->request->get("sort");
        $searchUserModel = new SearchUsers();
        $loginUser = $this->component->user->getSessionUser();
        $page = $this->request->get("page");
        $limit = 1;
        if (!$page){
            $page = 1;
        }
        $list = $searchUserModel->findTeachers($q, $loginUser->id, ($loginUser?true:false), $page, $limit, $sort);
        $list['status'] = true;
        echo json_encode($list);
    }

At first I am not sure if the res status is defined so I added $list['status'] = true but it is not helping. Then I tried to remove the if/else statements and it is also not effective.

I need another pair of eyes as I already confirmed all the other variables are valid (ie. $q, $loginUser, $page, $limit, $sort).

Will be greatly appreciated if you can let me know first before downvoting if you think my question is bad or unclear in the comments so I have a change to edit.

Aucun commentaire:

Enregistrer un commentaire