2

I am new to ajax and i am trying to store ratings for some songs i have on my website with a star rating system with the select tag but everytime i click on a specific star to rate the song it does nothing.The connection with the database is working and i guess there is something wrong in the javascript code below because if i enter the rating in the database manually with INSERT it does appear in the website

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="assets/jquery-bar-rating-master/dist/jquery.barrating.min.js"></script>
<!-- Invoke star rating -->
<script type='text/javascript'>
   $(document).ready(function(){
        $('#star_rating_<?php echo $song_id; ?>').barrating('set',<?php echo $rating; ?>);
    });
    $(function () {
        $('.rating').barrating({
            theme: 'fontawesome-stars',
            onSelect: function (value, text, event) {
                
                var el = this;
                var el_id = el.$elem.data('id');
                console.log(el_id);
                
                
                if (typeof (event) !== 'undefined') {
                    var split_id = el_id.split("_");
                    console.log(split_id);
                    var song_id = split_id[1];
                    console.log(song_id);
                    $.ajax({
                        url: 'ajax_star_rating.php',
                        type: 'post',
                        data: {
                            song_id: song_id,
                            rating: value
                        },
                        dataType: 'json',
                        success: function (data) {
                            var average = data['numRating'];
                            $('#numeric_rating_' + song_id).text(average);
                        }
                    });
                }
            }
        });
    });
</script>

Request-Response Error

Warning: Undefined array key "s_id" in C:\xampp\htdocs\site\ajax_star_rating.php on line 6 4 Fatal error: Uncaught TypeError: mysqli_fetch_array(): Argument #1 ($result) must be of type mysqli_result, bool given in C:\xampp\htdocs\site\ajax_star_rating.php:13 Stack trace: #0 C:\xampp\htdocs\site\ajax_star_rating.php(13): mysqli_fetch_array(false) #1 {main} thrown in C:\xampp\htdocs\site\ajax_star_rating.php on line 13

Database Code

CREATE TABLE `songs` (
  `id` int(11) NOT NULL,
  `song_title` varchar(40) NOT NULL,
  `genre` varchar(30) NOT NULL,
  `youtubelink` varchar(512) DEFAULT NULL,
  `album` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `ratings` (
  `id` int(11) NOT NULL,
  `u_id` int(11) NOT NULL,
  `s_id` int(11) NOT NULL,
  `rating` int(2) NOT NULL,
  `date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ajax_star_rating.php


<?php

include("registration/connection.php");

$user_id = 1;
$song_id = $_POST['s_id'];
$rating = $_POST['rating'];

// Check rating inside the table
$query = "SELECT COUNT(*) AS countSong FROM ratings WHERE s_id = " . $song_id . " and u_id = " . $user_id;
$result = mysqli_query($con, $query);
$getdata = mysqli_fetch_array($result);
$count = $getdata['countSong'];

if($count == 0){
 $insertquery = "INSERT INTO ratings(u_id, s_id, rating) values(". $user_id .", ". $song_id .", ". $rating .")";
 mysqli_query($con, $insertquery);
}else {
 $updateRating = "UPDATE ratings SET rating=" . $rating . " where u_id=" . $user_id . " and s_id=" . $song_id;
 mysqli_query($con, $updateRating);
}

// fetch rating
$query = "SELECT ROUND(AVG(rating),1) as numRating FROM ratings WHERE s_id=".$song_id;
$result = mysqli_query($con, $query) or die(mysqli_error());
$getAverage = mysqli_fetch_array($result);
$numRating = $getAverage['numRating'];
$return_arr = array("numRating"=>$numRating);

echo json_encode($return_arr);
?>
F1_lover
  • 23
  • 5
  • Can you open your network tab in your browser and show us request and response? – Salikh Gurgenidze Jun 02 '22 at 17:15
  • I edited my question with database code and some console feedback – F1_lover Jun 02 '22 at 17:31
  • It seems to me that you might be trying to save an array or string when the database expects an int. I think it would be important to see the `ajax_star_rating.php` code. – Slaveworx Jun 02 '22 at 17:32
  • @Slaveworx I added the ajax_star_rating.php in my question just now – F1_lover Jun 02 '22 at 17:37
  • what is the output of this? `$_POST['rating'];` ? can you echo it ? – Slaveworx Jun 02 '22 at 17:44
  • You're trying to get `$_POST['s_id'];`, but you're sending `song_id: song_id`. Look at the response in your Network tab, you should see some errors. – aynber Jun 02 '22 at 17:47
  • I am trying to echo this $_POST['rating']; but it doesnt work.. – F1_lover Jun 02 '22 at 18:08
  • @aynber i updated my question with the console log..thats all i see..no errors..dont know why – F1_lover Jun 02 '22 at 18:08
  • The console log only shows the javascript messages. If you click on the Network tab, you should see all of the network requests. Click on XHR, and it will show only requests sent via ajax. Click on the specific request to `ajax_star_rating.php`, and you should be able to see the Request and Response tabs. – aynber Jun 02 '22 at 18:10
  • @aynber ok now i understand..here.. Warning: Undefined array key "s_id" in C:\xampp\htdocs\site\ajax_star_rating.php on line 6 4 Fatal error: Uncaught TypeError: mysqli_fetch_array(): Argument #1 ($result) must be of type mysqli_result, bool given in C:\xampp\htdocs\site\ajax_star_rating.php:13 Stack trace: #0 C:\xampp\htdocs\site\ajax_star_rating.php(13): mysqli_fetch_array(false) #1 {main} thrown in C:\xampp\htdocs\site\ajax_star_rating.php on line 13 – F1_lover Jun 02 '22 at 18:16
  • So that goes back to `s_id` in your PHP script vs `song_id` in your javascript – aynber Jun 02 '22 at 18:21
  • @aynber ok but isnt this $song_id = $_POST['s_id']; making them the same variables? – F1_lover Jun 02 '22 at 18:26
  • No. `$_POST` contains all of the keys/values sent via the post request. You are sending `song_id` and `rating`, as you can see in your javascript. `s_id` does not exist anywhere. You can do `var_dump($_POST);` to see what all it contains – aynber Jun 02 '22 at 18:42
  • @aynber The s_id is in the ratings table..so what do i do..i am stuck :/ – F1_lover Jun 02 '22 at 18:51
  • I still think that you are trying to save an array to a “int” field. And also. It says you are providing a Boolean. So probably aynber is right. – Slaveworx Jun 02 '22 at 19:20
  • 1
    Either change `$_POST['s_id'];` to `$_POST['song_id'];` or change `song_id: song_id,` to `s_id: song_id,`. Ignore the database, that hasn't come into play yet. This is only about the communication between your javascript and the beginning of your PHP script. – aynber Jun 03 '22 at 13:02
  • Your next step will to be to use [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php). This will make sure all of your variables are put properly into your query and won't leave any gaping holes like the one you currently have. Since `$song_id` is empty, your query would look like `SELECT COUNT(*) AS countSong FROM ratings WHERE s_id = and u_id = 1`, which is invalid syntax. Using prepared statements will properly create a correct query, even if it doesn't return any results. – aynber Jun 03 '22 at 13:04
  • @aynber I changed $_POST['s_id']; to $_POST['song_id'] and it worked.Thanks dude – F1_lover Jun 03 '22 at 19:47

0 Answers0