Peter Wateber
Peter Wateber

Reputation: 3948

about json_encode and ajax dataType: "json"

In my ajax code:

$.ajax({
        url: CI_ROOT + "isUserExist",
        type: "GET",
        data: {recepient: recepient},
        success: function(r) {
            console.log(r)
        }
})

Gives me an output [{"records":"1"}][{"records":"1"}] So I parsed it to json by adding dataType: "json" in my ajax code. But when I parsed it, it doesn't give me output but error on try-catch-block.

How do I get it to display as objects? In my PHP code, I'm doing it this way:

 for ($i = 0; $i < count($matches[0]); $i++) {
     echo json_encode($this->searchmodel->doesUsersExists($matches[0][$i]));
 } //gets the user id of the user from a given string.

Upvotes: 0

Views: 454

Answers (2)

Paul
Paul

Reputation: 141887

Add each entry to an array and then json encode that array, instead of json encoding each one separately. If you only have one call to json_encode, you will get valid JSON:

$result = array();
for ($i = 0; $i < count($matches[0]); $i++) {
     $result[] = $this->searchmodel->doesUsersExists($matches[0][$i]);
} //gets the user id of the user from a given string.

echo json_encode($result);

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799200

That's not valid JSON. Make an array from your exist results and encode that.

Upvotes: 2

Related Questions