user3192948
user3192948

Reputation: 251

AJAX cannot return Json data

I'm trying to post a piece of Json data to AJAX and get a "upvote_message" in return. However, the "upvote_message" is returned as undefined.

Code:

<div class="media">
<div class="media-body">
<p align="right">
<span href="javascript:;" rel="1" class="upvote">Text to be replaced</span>
</p>
</div>
</div>

JS:

<script type="text/javascript">

$(function(){

$('.media .media-body .upvote').click(function(){ 

var this_a = $(this);
var comment_id = $(this).closest('span').attr('rel');

$.ajax({ 
type:"POST", 
url: base_url + "/upvote",
data:{comment_id : comment_id}, 
dataType: "json",

success: function(data,status){
if(data.state == 'succ')
{
this_a.html(upvote_msg);  
}
else
{
this_a.html(upvote_msg);
}
}
});

}); 
}); 
</script>

PHP

public function upvote (){  

$comment_id = $this->input->post('comment_id');

if($comment_id==5){
echo json_encode(array('state' => 'succ','upvote_msg'=>'haha')); 
}

else{ 
echo json_encode(array('state' => 'fail','upvote_msg'=>'bam')); 
} 
exit();

}
}

The PHP and AJAX's write-into part works fine. Data is also registered in database.

The issue is that the 'upvote_msg' is shown as "undefined" when being returned to the Javascript.

How to fix this? Many thanks,

Upvotes: 0

Views: 183

Answers (2)

Chirag Parekh
Chirag Parekh

Reputation: 496

To get upvote_msg value you have to use

data.upvote_msg or data["upvote_msg"]

Upvotes: 1

Musa
Musa

Reputation: 97672

upvote_msg is a property of the data object so it should be data.upvote_msg

Upvotes: 2

Related Questions