-1

I'm using Codeigniter and I have a form where user can rate a product. What I need to know is, when a star button is clicked and submitted, I need to insert into the database whichever star button is clicked.

If 5th button is clicked it'll display "Excellent" text. If 4th button is clicked it'll display "good" text.

So I need the users' rating to be inserted into the database.

<form name="myForm7" method="post" action="<?php echo 'http://localhost/ci/businessRateCtrl/insertIntoBusinessReview/'. $Vehicleid;  ?>">
  <h1>
    <div class="rating" style="width:200px;float:left;padding-left:1px">
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
      <span class="rate-star" data-rate="Excellent">&bigstar;</span>
      <span class="rate-star" data-rate="Good">&bigstar;</span>
      <span class="rate-star" data-rate="Okay">&bigstar;</span>
      <span class="rate-star" data-rate="Unsatisfied">&bigstar;</span>
      <span class="rate-star" data-rate="Terrible">&bigstar;</span>
    </div>
  </h1>


  <div style="float:right;padding-right:450px">
    <h3><label id="rateText" name="lblrating"></label></h3>
    <input type="hidden" id="rating" name="RatingTxt" value="" />
  </div>

  <script type="text/javascript">
    var rateText;
    window.onload = function() {
      var starList = document.getElementsByClassName('rate-star');
      var numOfStars = starList.length;

      for (var i = 0; i < numOfStars; i++) {
        starList[i].addEventListener('click', starClickHandler, false);
      }
    }

    function starClickHandler(event) {
      var star = event.currentTarget;

      setActive(star, false);
      setActive(star, true);
      document.getElementById('rateText').textContent = star.getAttribute('data-rate');

      rateText = document.getElementById('rateText').textContent
      document.getElementById('rating').value = rateText;

    }

    function setActive(element, isActive) {
      if (isActive) {
        element.classList.add('active');
        element.nextElementSibling && setActive(element.nextElementSibling, isActive);
      } else {
        element.classList.remove('active');
        element.previousElementSibling && setActive(element.previousElementSibling, isActive);
      }
    }

    $(document).ready(function() {
      $(".rating .rate-star").click(function() {
        $(".active").removeClass("active");
        $(".rate-star:lt(" + ($(this).index() + 1) + ")").addClass("active");
        $("#rateText").html($(this).data("rate"));
        $("#submitreview").removeAttr("disabled");
      });

    });


    function cancelConfirm() {
      return confirm("Are you sure you want to cancel and leave this page?");
    }
  </script>

  <style type="text/css">
    .active {

      color: yellow;
    }

    #rateText {

      text-align: right;

    }

    .rating {
      unicode-bidi: bidi-override;
      direction: rtl;
    }


    .rating>.rate-star.active,
    .rating>.rate-star:hover,
    .rating>.rate-star:hover~.rate-star {
      color: #FFFF00;
      cursor: default;
    }
  </style>

From the following code it assigns the text from the clicked button, into rateText label. Now I need that text to be passed to my controller through this form's action attribute (as a parameter).

document.getElementById('rateText').textContent = star.getAttribute('data-rate');

Is the following correct and if so, how can the rateText variable be added to the form's action attribute and sent to the controller?

<script type="text/javascript">
  var rateText;
  window.onload = function() {
    var starList = document.getElementsByClassName('rate-star');
    var numOfStars = starList.length;

    for (var i = 0; i < numOfStars; i++) {
      starList[i].addEventListener('click', starClickHandler, false);
    }
  }

  function starClickHandler(event) {
    var star = event.currentTarget;

    setActive(star, false);
    setActive(star, true);
    document.getElementById('rateText').textContent = star.getAttribute('data-rate');
    rateText = document.getElementById('rateText').textContent

  }

This code refreshes the page and displays the same content. It adds the following to the URL:

http://localhost/ci/businessRateCtrl/loadReviewPage/base_url();?%3EbusinessRateCtrl/insertIntoBusinessReview/base_url();

In the form's action attribute I used

action="<?php echo 'base_url();?>businessRateCtrl/insertIntoBusinessReview/'.$Vehicleid;?>"

but I don't know how is it appending http://localhost/ci/businessRateCtrl/loadReviewPage/ into the URL.

1
  • 1
    From a data structure standpoint you are much better off using a numbered rating system, it's one to five stars so making ratings an integer between 1-5 is efficient. Display whatever text you want based on that; calculating the average rating and things like that will be unnecessarily complex in the direction you are currently going though. Also calculating how many stars to show if you are in fact showing the filled in stars to represent what's selected. Numbers are easier. Commented Apr 6, 2016 at 21:17

2 Answers 2

1

It is unclear to me what you are doing right now. You can either set a hidden input which you then submit, which seems what you are trying to do?

Or you can do an AJAX request which wouldn't require to do a submit, meaning no refresh which usually gives a much better user experience.

Read more about AJAX requests here: http://api.jquery.com/jquery.ajax/

P.S. there are examples at the bottom of the page.

For submitting it through a form, ad a hidden input to your form:

<input type="hidden" id="rating" value="" />

and then when you want to assign its value in your function:

function starClickHandler(event) {
    var star = event.currentTarget;

    setActive(star, false);
    setActive(star, true);
    document.getElementById('rateText').textContent = star.getAttribute('data-rate');
    rateText = document.getElementById('rateText').textContent 
    document.getElementById('rating').value = rateText;

}

I think that should work, as others have said it's probably better to use numeric values instead of strings to save in your database

Sign up to request clarification or add additional context in comments.

4 Comments

When user click star buttons, think user clicked 5th star button then in front of that, a label will display saying "Excellent".Now what i want to do is to when form is submitted ,i need to take whatever "Excellent" or a data regarding that rating to take into the controller. then i can insert into the db.If that successful , then i can view the rating in another page even.that is what i need to do . hope you can clear it out now? for me actually i didn't understand what you said "you can either set a hidden input " like this here
I understand what you want, so what have you tried? like i said you can add an input with type="hidden" and set the value just like you did text element that shows it to the user.
I kindly requesting from you to explain it with a code. i don't have any idea to how to do it.Please Kindly consider about it
stackoverflow.com/questions/7764154/… i'll add a short example to answer, but it's same as there. (going to sleep after)
1

I suggest using jQuery and AJAX call instead of JavaScript.

With an AJAX call you can get the value of your stars and pass it to a PHP page for saving into a database without reloading the page. Here is a quick example:

Your HTML is OK.

jQuery:

$('.rate-star').click(function(){
    var ratestar=$(this).data('rate');
        $.ajax({
            type: "POST",
            url: "../ajax/ajax-rate.php",//here your php page
            cache: false,
            dataType: "json",
            data: {
                rate: ratestar              
            },
            success: function (data) {
                //if the ajax is done correctly enter in success   
              if(data.error==false){
                $('#rateText').html(ratestar);
              }else{
                 //handle your error
               }
            },
            error: function (e, t, n){
            //if there are some problems with the ajax request enter here
            }
        });
    });

ajax-rate.php:

<?php
if(isset($_POST['rate'])){
    $rate = $_POST['rate'];
    
    //now save it into the db as you usually do
    $message['message'] = 'some message if you need';
    $message['error'] = false //this is not the error ajax function but it can helps you in the susseccs ajax function to handle errors
    
    echo json_encode($message);
}
?>

Documentation: http://api.jquery.com/jquery.ajax/

11 Comments

Now i'm using codeigniter. So this ajax-rate.php is a controller here?, can you please correct me? and for url you have used this.that two dots (..) means i need to add their something? and also in my forms' action attribute i need to call to ajax-rate.php and then after if condition if(isset($_POST['rate'])){ $rate=$_POST['rate']; i need to call to the controller which is responsible for inserting the data into db. These question may be somewhat silly but can you kindly consider about it and explain it. as I'm a beginner to programming.
yeah in my code i don't consider code igniter because i don't use it but you can adapt it. I use the two dots only because the html page isn't in the same root of the ajax-rate.php so you have to remove all my path and add your padd using the function url of codigniter.There is no form on click of an element with the class rate-star the ajax call start.Yes after $rate.. use your code for insert the variavble rate into the database.I don't now exactly if you have to consider ajax-rate as a controller because is a simple page of php that run aside and than respond
search some example like this one formget.com/codeigniter-jquery-ajax-post hope it helps
to url do i need to give the path to the ajax-rate.php?
yeah use base_url() function of codeingiter ond use the right path
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.