William William - 6 months ago 46
JSON Question

json_encode returns 200 and undefined

I'd like to have a code to add or remove from database bookmarks.
The code is ready and it adds and removes from database bookmarks correctly, but when I call the function it keeps returning the

json error
instead
json success
even if the code works.

I'd like to know what's wrong with the code (that I got and adapt from somewhere else) because the client side is not receiving the correct values
true
or
false
, it only triggers the
json beforeSending
and
json error
.

server side:

if($isFavorite) {
// if it's favorite, remove from bookmarks
return json_encode(array("status" => true, "added" => false));
} else {
// if it's not favorite, include into bookmarks
return json_encode(array("status" => false, "added" => true));
}


client side:

<script>
function addItemToUsersList(userId, type, itemId) {
jQuery.ajax({
'url': 'xxx',
'type': 'GET',
'dataType': 'json',
'data': {userid: userId, type: type, itemid: itemId},
'success': function(data) {
console.log('json success');
},
'beforeSend': function() {
console.log('json beforeSending');
},
'error': function(data) {
console.log('json error');
console.log(data.status + ' ' + data.added);
}
});
}
</script>


The
console.log(data.status + ' ' + data.added);
line logs
200 undefined


How may I return the correct values
true
or
false
for both
"status"
and
"added"
?




Edit:
The
json success
is never logged on console, so I don't know what happened on server side. I need to know this because I need to change the class of an element to display an empty or yellow star.

Answer

If you are returning the result and not doing anything with that return elsewhere, you will not get any response to your ajax call, so it's undefined. As @MikeC says, you must echo it at some point.

If you are not already echoing it elsewhere, try:

$response = array(
    'status' => $isFavourite,
    'added' => !$isFavourite
);
echo json_encode($response);

My suggestion is also if 'status' and 'added' are really just the opposite of each other every time, then you probably only need to send 'status' on its own. In your JS you can just check 'status' and reverse the boolean as I've done above, if you want to know what the value of added would be.

 var added = !data.status;

Update

If your ajax request is coming back to the error function, the request itself is probably failing.

Change your error function to this, to debug what has happened:

'error': function(jqXHR, status, error) {
    console.log(status);
    console.log(error);
}

You might have an error in server-side code somewhere or you're calling the wrong PHP script perhaps?