rhill45
rhill45

Reputation: 569

GET or POST with AJAX

Trying to modify the RateIT star rating system to store votes in SQL db. Upon user input the script runs and mySQL records the data. However I am unable to receive an updated average value from SQL.

How do Run a query and send it back to AJAX and display it. Should POST or GET be used?

Im extremely confused, struggling with this for days. I've looked at examples and previous questions here and with RateIT but nothing seems to fit .

Code: would like the results to display in id="response"

HTML and JS

    <div id="products">
       <div>
         <ul id="response">
         </ul>
       </div>    
    </div>

    <script type ="text/javascript">
         $('#products .rateit').bind('rated reset', function (e) {
             var ri = $(this);
     var value = ri.rateit('value');
             var productID = ri.data('productid');
              ri.rateit('readonly', true);
             $.ajax({
                 url: 'rate.php',
                 data: { productID: productID, value: value }, 
                 type: 'POST',
                 success: function (data) {
                     $('#response').append('<li>' + data + '</li>');
                 },
                 error: function (jxhr, msg, err) {
                     $('#response').append('<li style="color:red">' + msg + '</li>');
                 }
             });
         });
    </script>

PHP

     <?PHP
        $con=mysqli_connect ("host","user","pass#","dbname");
        mysqli_query($con,"INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[productID]','$_POST[value]',now())");
        mysqli_close($con);
        exit;
              ?>

Thank you in advance!

edited php code:

$result=mysqli_query($con,"INSERT INTO ratings (storyidr, rank, entry_date)          VALUES        ('$_POST[storyidr]','$_POST[value]',now()) THEN SELECT AVG(rank) AS avrank from ratings WHERE storyidr=$storyidr;" );

$avgrate = $data['avrank'];
if(!$result)
 {
  $arr = array ('status'=>'fail');
  echo json_encode($arr);
}
else
{
     $arr = array ($avgrate);
    echo json_encode($arr);
}
    exit;
?>

Upvotes: 0

Views: 136

Answers (1)

Ankur Aggarwal
Ankur Aggarwal

Reputation: 3101

You can use the JSON format to send back the result using json_encode

$result=mysqli_query($con,"INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[productID]','$_POST[value]',now())");

if(!$result)
{
      $arr = array ('status'=>'fail');
      echo json_encode($arr);
}
else
{
        $arr = array ('status'=>'success');
        echo json_encode($arr);
}

In the success callback you can have the status using object.status (data.status in your case)

Upvotes: 1

Related Questions