0

i'm working on a small "facebook like" application for a school project and i'm having some issue with an Ajax request i'm trying to do a like dislike systeme with Jquery Ajax but i got this error in the console when i debug my "data"

Uncaught SyntaxError: Unexpected token < in JSON at position 4

This is my ajax call :

$(document).ready(function(){
$('.like-btn').on('click', function(){
var post_id = $(this).data('id');
$clicked_btn = $(this);
if ($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up')) {
var action = 'like';
} else if($clicked_btn.hasClass('glyphicon glyphicon-thumbs-up liked')){
var action = 'unlike';
}
$.ajax({
type: "POST",
url: 'index.php?action=likes',
data:{
    'action': action,
    'post_id': post_id
},
success: function(data){
    alert("succes");
    console.log(data);
    res = JSON.parse(data);
    if (action == "like") {
        $clicked_btn.removeClass('glyphicon glyphicon-thumbs-up');
        $clicked_btn.addClass('glyphicon glyphicon-thumbs-up liked');
    } else if(action == "unlike") {
        $clicked_btn.removeClass('glyphicon glyphicon-thumbs-up liked');
        $clicked_btn.addClass('glyphicon glyphicon-thumbs-up');
    }
    // Affiche le nombre de like dislike
    $clicked_btn.siblings('span.likes').text(res.likes);
    $clicked_btn.siblings('span.dislikes').text(res.dislikes);

    // Change le style du boutton suivant si user click dessus
    $clicked_btn.siblings('glyphicon glyphicon-thumbs- 
    down').removeClass('glyphicon glyphicon-thumbs- 
    down').addClass('glyphicon glyphicon-thumbs-down disliked');
    }, error: function(jq,status,message) {
    alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' 
    + message);
    console.log(status + message);
    }
    });     

    });

And this is my likes.php :

<?php
function getRating($id)
{
global $pdo;
$rating = array();
$likes_query = "SELECT COUNT(*) FROM rating_info WHERE post_id = ? AND 
rating_action='like'";
$dislikes_query = "SELECT COUNT(*) FROM rating_info 
                WHERE post_id = ? AND rating_action='dislike'";
$likes_rs = $pdo->prepare($likes_query);
$dislikes_rs = $pdo->prepare($dislikes_query);
$likes_rs->execute(array($id));
$dislikes_rs->execute(array($id));
$likes=$likes_rs->fetch();
$dislikes=$dislikes_rs->fetch();
$rating = [
'likes' => $likes[0],
'dislikes' => $dislikes[0]
];
return json_encode($rating);
}



if (isset($_POST['action'])) {
$user_id=$_SESSION['id'];
$return = $_POST;
$post_id = $_POST['post_id'];
$action = $_POST['action'];
switch ($action) {
case 'like':
     $sql="INSERT INTO rating_info (user_id, post_id, rating_action) 
           VALUES ($user_id, $post_id, 'like') 
           ON DUPLICATE KEY UPDATE rating_action='like'";
     break;
case 'dislike':
      $sql="INSERT INTO rating_info (user_id, post_id, rating_action) 
           VALUES ($user_id, $post_id, 'dislike') 
           ON DUPLICATE KEY UPDATE rating_action='dislike'";
     break;
case 'unlike':
      $sql="DELETE FROM rating_info WHERE user_id=$user_id AND 
post_id=$post_id";
      break;
case 'undislike':
      $sql="DELETE FROM rating_info WHERE user_id=$user_id AND 
post_id=$post_id";
  break;
default:
    break;
}


$q = $pdo->prepare($sql);
$q->execute();

echo getRating($post_id);
exit(0);
}

I've tried using datatype:'json' but it also return me an error , Actually it work to insert value in my DB, but it doesnt handle the change of the css and i've got this error. I'm not use to Ajax this might be simple, sorry if i'm saying a stupid question. Thanks you in advance for you time and messages, see ya.

ruko kei
  • 13
  • 2
  • 1
    What do you see in the console as the output for the console.log(data) line? I've gotten similar errors when I'm getting a response I wasn't expecting. – Peter Breen Nov 12 '18 at 19:14
  • 2
    Usually this error means the server is returning HTML instead of JSON. Check what your PHP is outputting. I see you're sending your AJAX request to index.php. This is usually the main page of your site. it's much better to separate the generating of JSON data and HTML data into separate scripts. I would remove all the PHP code shown above into a separate script which does nothing else, and then call that script specifically in your AJAX request. Probably you've also inadvertently output some HTML along with the JSON. – ADyson Nov 12 '18 at 19:15
  • P.S. Your insert queries are vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Nov 12 '18 at 19:16
  • @PeterBreen Yes the error is the result of the console.log – ruko kei Nov 12 '18 at 20:12
  • Possible duplicate of ["SyntaxError: Unexpected token < in JSON at position 0" in React App](https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0-in-react-app) – miken32 Nov 12 '18 at 20:29
  • @ADyson Thanks you for your help, yes in fact what i've got in return is the html thanks you for the informations about sql Injection, our professor talked about it briefly. I understand it's importance i'will do what you said, make the php in its own file and see what the result see ya – ruko kei Nov 12 '18 at 20:35

1 Answers1

0

I found the solution thanks you @ADyson, first of all i've changed my php in it's own file and i've also parameterised my queries in the php file, so yes i think the problem was in my index.php thanks you all

ruko kei
  • 13
  • 2