0

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,

Dinesh Saini
2,9162 gold badges36 silver badges50 bronze badges
asked Jan 18, 2014 at 2:25

2 Answers 2

2

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

answered Jan 18, 2014 at 2:29

Comments

1

To get upvote_msg value you have to use

data.upvote_msg or data["upvote_msg"]
answered Jan 18, 2014 at 5:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.