0

I'm using ajax jquery in PHP to create a rating system with database data. so far I could get the result like this. enter image description here

I want this to correct as I showed using arrows. how to achieve that output?

here is the code.

fetchrate.php

<?php

//fetch.php

$connect = new PDO('mysql:host=localhost;dbname=manpower', 'root', '');

$query = "
SELECT * FROM supplier_job WHERE jobStatus='offline' order by jobID DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
    $rating = count_rating($row['jobID'], $connect);
    $color = '';
    $output .= '

 <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
 ';

    for($count=1; $count<=5; $count++)
    {
        if($count <= $rating)
        {
            $color = 'color:#ffcc00;';
        }
        else
        {
            $color = 'color:#ccc;';
        }
        $output .= '<li title="'.$count.'" jobID="'.$row['jobID'].'-'.$count.'" data-index="'.$count.'"  data-job_id="'.$row['jobID'].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:16px;">&#9733;</li>';
    }
    $output .= '
 </ul>
 ';
}
echo $output;

function count_rating($job_id, $connect)
{
    $output = 0;
    $query = "SELECT AVG(rating) as rating FROM ratings WHERE job_id = '".$job_id."'";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $total_row = $statement->rowCount();
    if($total_row > 0)
    {
        foreach($result as $row)
        {
            $output = round($row["rating"]);
        }
    }
    return $output;
}


?>

here is the file with HTML part supplier_jobs_accept.php

<?php
$servername="localhost";
$username="root";
$password="";
$databasename="manpower";

//create connection
$conn=mysqli_connect($servername,$username,$password,$databasename);

    $queryJob="SELECT * FROM supplier_job WHERE jobStatus='offline' order by jobID DESC";

    $resultJob=mysqli_query($conn,$queryJob);
    if(mysqli_num_rows($resultJob)>0){
        while($rowJob=mysqli_fetch_assoc($resultJob)){

            $locationID=$rowJob['locationID'];
            $queryLocation="SELECT * FROM location WHERE locID='$locationID'";
            $resultLocation=mysqli_query($conn,$queryLocation);

            $rowLocation=mysqli_fetch_assoc($resultLocation);
            $locationName=$rowLocation['locName'];
            $locationAddress=$rowLocation['locStreet'].", ".$rowLocation['locVillage'].", ".$rowLocation['locCity'];


            echo "
<html>
<head>
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js\"></script>
  <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" />
  <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>
</head>

<div class='single-post d-flex flex-row'><div class='thumb'>
                    <img src='../img/img-worker/post.png' alt=''>
                    </div>
                <div class='details'>
                    <div class='title d-flex flex-row justify-content-between'>
                        <div class='titles'>
                            <a href=''><h4>".$rowJob['jobTitle']."<small> Published on ".$rowJob['jobPublished']."</small></h4></a>
                            <h6>By ".$locationName."</h6>   
                          <span id=\"job_list\"></span> 


                        </div>
                        <ul>
                            <li><a class='btn btn-primary' href='./query_boxes/supplier_jobs_accept_accept_jobs.php?jobID=".$rowJob['jobID']."'>Apply</a></li>
                        </ul>
                    </div>
                    <p >".$rowJob['jobCount']." pieces needs to do ".$rowJob['jobType'].". Every manpower member has to work at most ".$rowJob['jobPeriod']." days. 
                    <strong></strong> Job should be complete within ".$rowJob['jobPeriod']." days.</p>

                    <h5>Job Nature: ".$rowJob['jobNature']."</h5>
                    <p class='address'><span class=''></span>".$locationAddress."</p>
                    <p class='address'><span class=''></span>".$rowJob['workersJoined']." joined.</p>
                </div></div>


        </html>

        ";






        }
    }

?>
<script>
    $(document).ready(function(){

        load_supplier_jobs_accept_data();

        function load_supplier_jobs_accept_data()
        {
            $.ajax({
                url:"fetchrate.php",
                method:"POST",
                success:function(data)
                {
                    $('#job_list').html(data);
                }
            });
        }

        $(document).on('mouseenter', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            remove_background(job_id);
            for(var count = 1; count<=supplier_jobs_accept; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ffcc00');
            }
        });

        function remove_background(job_id)
        {
            for(var count = 1; count <= 5; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ccc');
            }
        }

        $(document).on('mouseleave', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            var rating = $(this).data("rating");
            remove_background(job_id);
            //alert(rating);
            for(var count = 1; count<=rating; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ffcc00');
            }
        });

        $(document).on('click', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            $.ajax({
                url:"insert_rating.php",
                method:"POST",
                data:{supplier_jobs_accept:supplier_jobs_accept, job_id:job_id},
                success:function(data)
                {
                    if(data == 'done')
                    {
                        load_supplier_jobs_accept_data();
                        alert("You have rate "+supplier_jobs_accept +" out of 5");
                    }
                    else
                    {
                        alert("There is some problem in System");
                    }
                }
            });

        });

    });
</script>

stars of the rating are getting from the span tag called joblist. can anyone help with this problem?

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
Pasindu
  • 340
  • 1
  • 8
  • 24
  • supplier_jobs_accept.php: change the 1. to 2. $('#job_list').html(data); to //json data from php result = JSON.parse(data); $.each(data, function(i, item) { $('.job-list-'+item.id).html(item.output); }); – Naushad Jan 04 '19 at 05:54
  • can you give it as an answer. then i can rate it as well – Pasindu Jan 04 '19 at 05:58
  • fetchrate.php change 1. $output = ''; foreach($result as $row) { to $output = ''; // add array to handle html data $jobs = array(); foreach($result as $row) { 2. $output .= ' '; }echo $output; to $output .= ' '; $jobs[$i]['id'] = $row['jobID']; $jobs[$i]['output'] = $output; $i++;}//use json for sending data ajaxecho json_encode($jobs); – Naushad Jan 04 '19 at 05:59
  • please give this as an answer intead of a comment :) – Pasindu Jan 04 '19 at 06:00

2 Answers2

0

I would create an array of each rating in the PHP script instead of concatenating them all to a string. In fetchrate.php, define $output as an array instead of a string. In the foreach, define a temporary string that you will add everything to instead of $output. Then at the end of each iteration, append that temporary string to $output.

You can then send the data as encoded JSON. Here's a quick summary of that link:

JSON encode the output before responding with it: echo json_encode($output)

In your AJAX body, add a data type header that's assigned to JSON:

$.ajax({
    ...
    dataType: 'json',
    ...
});

In your callback, the data parameter should now be an array.

Now for the spans displaying the stars, I think the easiest way with the current structure (trying to keep the structure) is to index the ids of the job_list spans: set up a counter starting at 0 that is incremented each iteration of the while loop in supplier_jobs_accept.php. Suppose it's called i, then define the span like <span id=\"job_list' + i + '\"></span> so they're indexed (job_list0, job_list1, ...). Then in the AJAX callback, run an index loop through the data and update the appropriate span's html:

for (var i = 0; i < data.length; i++) {
    $('#job_list' + i).html(data[i]);
}
0

supplier_jobs_accept.php

<?php
$servername="localhost";
$username="root";
$password="";
$databasename="manpower";
//create connection
$conn=mysqli_connect($servername,$username,$password,$databasename);
$queryJob="SELECT * FROM supplier_job WHERE jobStatus='offline' order by jobID DESC";
$resultJob=mysqli_query($conn,$queryJob);
if(mysqli_num_rows($resultJob)>0){
        while($rowJob=mysqli_fetch_assoc($resultJob)){

            $locationID=$rowJob['locationID'];
            $queryLocation="SELECT * FROM location WHERE locID='$locationID'";
            $resultLocation=mysqli_query($conn,$queryLocation);

            $rowLocation=mysqli_fetch_assoc($resultLocation);
            $locationName=$rowLocation['locName'];
            $locationAddress=$rowLocation['locStreet'].", ".$rowLocation['locVillage'].", ".$rowLocation['locCity'];

            echo "
<html>
<head>
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js\"></script>
  <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" />
  <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>
</head>

<div class='single-post d-flex flex-row'><div class='thumb'>
                    <img src='../img/img-worker/post.png' alt=''>
                    </div>
                <div class='details'>
                    <div class='title d-flex flex-row justify-content-between'>
                        <div class='titles'>
                            <a href=''><h4>".$rowJob['jobTitle']."<small> Published on ".$rowJob['jobPublished']."</small></h4></a>
                            <h6>By ".$locationName."</h6>   
                          <span class=\"job-list-\"".$rowJob['jobID']."></span> 


                        </div>
                        <ul>
                            <li><a class='btn btn-primary' href='./query_boxes/supplier_jobs_accept_accept_jobs.php?jobID=".$rowJob['jobID']."'>Apply</a></li>
                        </ul>
                    </div>
                    <p >".$rowJob['jobCount']." pieces needs to do ".$rowJob['jobType'].". Every manpower member has to work at most ".$rowJob['jobPeriod']." days. 
                    <strong></strong> Job should be complete within ".$rowJob['jobPeriod']." days.</p>

                    <h5>Job Nature: ".$rowJob['jobNature']."</h5>
                    <p class='address'><span class=''></span>".$locationAddress."</p>
                    <p class='address'><span class=''></span>".$rowJob['workersJoined']." joined.</p>
                </div></div>
        </html>
        ";
        }
    }

?>
<script>
    $(document).ready(function(){

        load_supplier_jobs_accept_data();

        function load_supplier_jobs_accept_data()
        {
            $.ajax({
                url:"fetchrate.php",
                method:"POST",
                success:function(data)
                {
                    //json data from php
                    result = JSON.parse(data);
                    $.each(data, function(i, item) {                        
                        $('.job-list-'+item.id).html(item.output);
                    });

                }
            });
        }

        $(document).on('mouseenter', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            remove_background(job_id);
            for(var count = 1; count<=supplier_jobs_accept; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ffcc00');
            }
        });

        function remove_background(job_id)
        {
            for(var count = 1; count <= 5; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ccc');
            }
        }

        $(document).on('mouseleave', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            var rating = $(this).data("rating");
            remove_background(job_id);
            //alert(rating);
            for(var count = 1; count<=rating; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ffcc00');
            }
        });

        $(document).on('click', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            $.ajax({
                url:"insert_rating.php",
                method:"POST",
                data:{supplier_jobs_accept:supplier_jobs_accept, job_id:job_id},
                success:function(data)
                {
                    if(data == 'done')
                    {
                        load_supplier_jobs_accept_data();
                        alert("You have rate "+supplier_jobs_accept +" out of 5");
                    }
                    else
                    {
                        alert("There is some problem in System");
                    }
                }
            });

        });

    });
</script>      

fetchrate.php

<?php

//fetch.php

$connect = new PDO('mysql:host=localhost;dbname=manpower', 'root', '');

$query = "
SELECT * FROM supplier_job WHERE jobStatus='offline' order by jobID DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
// add array to handle html data
$jobs = array();
foreach($result as $row)
{
    $i= 0;
    $rating = count_rating($row['jobID'], $connect);
    $color = '';
   $output .= '



 <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
 ';

    for($count=1; $count<=5; $count++)
    {
        if($count <= $rating)
        {
            $color = 'color:#ffcc00;';
        }
        else
        {
            $color = 'color:#ccc;';
        }
        $output .= '<li title="'.$count.'" jobID="'.$row['jobID'].'-'.$count.'" data-index="'.$count.'"  data-job_id="'.$row['jobID'].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:16px;">&#9733;</li>';
    }
    $output .= '
 </ul>
 ';
 $jobs[$i]['id'] = $row['jobID'];
 $jobs[$i]['output'] = $output;
 $i++;
}
//use json for sending data ajax
echo json_encode($jobs);


function count_rating($job_id, $connect)
{
    $output = 0;
    $query = "SELECT AVG(rating) as rating FROM ratings WHERE job_id = '".$job_id."'";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $total_row = $statement->rowCount();
    if($total_row > 0)
    {
        foreach($result as $row)
        {
            $output = round($row["rating"]);
        }
    }
    return $output;
}


?>
Naushad
  • 126
  • 1
  • 3