ReeseB
ReeseB

Reputation: 297

AJAX JQuery not updating span text

I am using a star rating script here, the script updates my database correctly but the returned text in my spans (avgrat and totalrat) are not updated. The variables in between both span tags should be updated with the returned values.

Returned value:

echo json_encode($ratingRow);

HTML

<div class="col-sm-3">
  <?php echo form_open('http://localhost/mysite/rating/rate'); ?>
  <input name="rating" value="<?php echo $ratingRow['stars']; ?>" id="rating_star" type="hidden" postID="<?php echo $nsid; ?>" />
  <div class="overall-rating">
    Overall Rating of <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span> Based on <span id="totalrat"><?php  echo $ratingRow['rating_number'] ?></span> votes.
  </div>
  <?php echo form_close(); ?>
</div>

Script

<script type="text/javascript">
  $(function() {
    $("#rating_star").codexworld_rating_widget({
      starLength: '5',
      initialValue: $('#rating_star').val(),
      callbackFunctionName: 'processRating',
      imageDirectory: '<?php echo base_url(); ?>i/icon',
      inputAttr: 'postID'
    }); 
  });

  function processRating(val, attrVal){
    $.ajax({
      type: 'POST',
      url: '<?php echo base_url(); ?>rating/rate',
      data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', "postID":attrVal, "ratingPoints":val},
      dataType: 'json',
      success : function(data) {
        if (data.status == 'ok') {
          $("span#avgrat").text($(this).data("average_rating"));
          $("span#totalrat").text($(this).data("rating_number"));
        }else{
          alert('Some problem occured, please try again.');
        }
      }
    });
  }
</script>

Upvotes: 1

Views: 1167

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Change these:

$("span#avgrat").text($(this).data("average_rating"));
$("span#totalrat").text($(this).data("rating_number"));

To these:

data = JSON.parse(data);
$("span#avgrat").text(data[0]["average_rating"]);
$("span#totalrat").text(data[0]["rating_number"]);

You cannot use this there. The this there refers to the success function. You have to first parse the data using JSON.parse(data). So it becomes a JavaScript Object from a string. This is optional, as you have already used dataType: "json". Now it should work for you as expected.

The data is an object and not a function. You have used data("rating_number"), which should be data[0]["rating_number"] and so on. Kindly check the updated answer.

Upvotes: 2

Related Questions