Reputation: 253
I have an ajax function that retrieve two values for a given post: one for the number of likes, another one for the div
that contains all the people that liked that post.
Everything seems to work fine, the json retrieved is correct, but the printing result is incorrect. Every time I try to get the number of likes (data.numDiLikes
) I always get undefined
even though the json is saying {"numDiLikes":"1","personeACuiPiace":"div info and stuff"}
, how do I fix this?
AJAX with JSON
$.ajax({
dataType: "json",
type: 'POST',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(data, textStatus){
trova.find('.numDiLikes').first().replaceWith('<p class="numDiLikes">' + data.numDiLikes + ' mi piace</p>' + data.personeACuiPiace);
}
});
PHP
if ($_POST['comOrisp'] == 'commento') {
$commento->set_likes($_POST['id'], true);
// number of people that liked the post
$return_data['numDiLikes'] = $commento->get_likes($_POST['id'], true);
// div with all the people who liked the post
$return_data['personeACuiPiace'] = $commento->posso_fare_qualcosa($_SESSION['auth'], 'cancRisp', $_POST['id']);
echo json_encode($return_data);exit;
}
Upvotes: 1
Views: 30
Reputation: 781058
Use dataType: "json"
to tell $.ajax
that it returns JSON, and that it should parse it. dataType: "html"
means that it returns HTML text, and data
will be a string, not an object.
Upvotes: 1