Search code examples
phpjqueryvote

onclick pass two variables to php with jquery (vote system)


I have 5 stars system in html/smarty below

<ul class="star-rating" id="{$ID}">
<li><a href="#" class="one-star"></a></li>
<li><a href="#" class="two-stars"></a></li>
<li><a href="#" class="three-stars"></a></li>
<li><a href="#" class="four-stars"></a></li>
<li><a href="#" class="five-stars"></a></li>
</ul>

<div style="display:none;" id="ok">Vote submited</div>
<div style="display:none;" id="wrong">Wrong</div>
<div style="display:none;" id="loggedin">Log in to vote</div>

ul blocks has own ID. I need to pass witch star has been pressed and get ul id, theen this data need to be passed to php and get response, theen response need to fade out. I came up with some basic code below, but it need's to be finished and fixed. Would be gratefull if anyone would be helpfull ?

$( ".star-rating" ).click(function() {

    $.ajax({ 
        type: "POST",
        url: "js/ajax.php",
        data: "id" + id, "score" + score,
        success: function(pass) {
                      // all ok
            if(pass == '1') 
                 $("#ok").show();
                      // something went wrong
            else if(pass == '2') 
                 $("#wrong").show();
                         // you need to be logged in to vote
            else if(pass == '3') 
                 $("#loggedin").show();
        }
    });
});

Solution

  • It sounds like you want to bind to the a and not the ul:

    $('ul.star-rating').on('click', 'a', function() { // jquery 1.7+
      var score = this.className,
          ul = $(this).closest('ul'),
          id = ul[0].id;
    
      $.ajax({ 
            type: "POST",
            url: "js/ajax.php",
            data: {id: id, score: score}, // fixed formatting here
            success: function(pass) {
                          // all ok
                if(pass == '1') 
                     $("#ok").show().delay(5000).fadeOut(); // here is one way to do a fade out
                          // something went wrong
                else if(pass == '2') 
                     $("#wrong").show();
                             // you need to be logged in to vote
                else if(pass == '3') 
                     $("#loggedin").show();
            }
        });
        return false;
    });
    

    Note also the delay in your succes callback as one way to do a fade.