Skip to content
Advertisement

Uncaught SyntaxError: Unexpected token < in JSON at position

I am currently trying to make a system of “favorites”. It works correctly but in the console of my browser gives an error (image below) and I do not understand why it happens.
I tried to find solutions but I can not understand them at all. Can anyone help me?

index.php:

        <div class="blog-fav">
            <i <?php if (userLiked($post['id'])): ?>
          class="fas fa-heart favorite like-btn" 
      <?php else: ?>
          class="fas fa-heart single like-btn"
      <?php endif ?>
      data-id="<?php echo $post['id'] ?>"></i>
        </div>

scripts.js:

    $(document).ready(function(){
    
    $('.like-btn').on('click', function(){
      var post_id = $(this).data('id');
      $clicked_btn = $(this);
      if ($clicked_btn.hasClass('single')) {
        action = 'like';
      } else if($clicked_btn.hasClass('favorite')){
        action = 'unlike';
      }
      $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            'action': action,
            'post_id': post_id
        },
        success: function(data){
            res = JSON.parse(data);
            if (action == "like") {
                $clicked_btn.removeClass('favorite');
                $clicked_btn.addClass('single');
            } else if(action == "unlike") {
                $clicked_btn.removeClass('single');
                $clicked_btn.addClass('favorite');
            }
        }
      });       
    });
  });

The error I get:

ERROR MESSAGE – IMG

Advertisement

Answer

The problem is in the excerpt res = JSON.parse (data);, the return from AJAX is HTML, but you are treating it as JSON.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement