Robert Mailloux
Robert Mailloux

Reputation: 397

Voting Page using AJAX/JQuery

I am trying to figure this out and I think I am almost there but I am stuck figuring out how to use the variables properly.

I am making a page that allows a user to vote on one of three color M&Ms. By clicking the picture of one of the M&M's on the main html page, your vote will be carried over to a php page using JQuery/AJAX, and the PHP page will then update teh DBase.

My PHP page and Dbase are fine. I am stuck trying to figure out how exactly I can format my HTML page to send over the proper info to my php page so that when the red M&M is clicked, that info will go, the blue, etc etc.

Here are my HTML links:

<div id="red">
<a href="#"><img src="images/red.jpg" width="100%" /></a>
</div>

<div id="blue">
<a href="#"><img src="images/blue.jpg" width="100%" /></a>
</div>

<div id="green">
<a href="#"><img src="images/green.jpg" width="100%" /></a>
</div>

and I want to send these over to my PHP page using JQuery and AJAX to then receive the updated vote counts. How would I formulate the AJAX/jQuery command so that when each link is clicked it sends over the color for that link? I dont need exact code here, just a pointer or two will help.

Upvotes: 1

Views: 691

Answers (4)

Kesymaru
Kesymaru

Reputation: 129

Is simple.

/****** JQUERY *******/

/**
* SEND NEW VOTE
* @param int color id of color
*/
function SendVote(color){
    var count = '';
    if( color == 1){
        count = 'red';
    }
    if( color == 2){
        count == 'blue';
    }
    if( color == 3){
        count == 'green';
    }

    //send data via ajax,
    var queryParams = {'color':color};
    $.ajax({
        data: queryParams,
        type: "post",
        url: 'path/to/vote.php'
        beforeSend: function(){ // here you could add a loader (if you want)
            //show loader 
        },
        success: function(response){ // success here you get the response from the server
            //response is not empty
            if( response.length > 0){
                $("#"+count+' span').html(response+' votes'); // then change the number of the counter
            }else{
                //and error on php, cause there response but is empty
            }
        },
        fail: function(e){ //get fail ajax errors
            console.log('fail '+e);
        },
        error: function(e){ // get errors
            console.log('error '+e);
        }
    });
}

/*** ON vote.php (or your php script) *****/

if( isset($_POST['color']) ){

    //do the things to add the new vote

    //then echo the total of votes for the color
    echo getVotes($_POST['color']); //this is the response that ajax will get
}

/********** html *******/

<div id="red">
<a href="#" onclick="SendVote(1)"><img src="images/red.jpg" width="100%" /></a>
<span>
    5 votes
</span>
</div>

<div id="blue">
<a href="#" onclick="SendVote(2)"><img src="images/blue.jpg" width="100%" /></a>
<span>
    4 votes
</span>
</div>

<div id="green">
<a href="#" onclick="SendVote(3)"><img src="images/green.jpg" width="100%" /></a>
<span>
    0 votes
</span>
</div>

Upvotes: 0

Pitchinnate
Pitchinnate

Reputation: 7566

Nick's answer is good just thought I would give you one more option:

<div id="red">
<a href="/vote.php?color=red" class='vote'><img src="images/red.jpg" width="100%" /></a>
</div>

<div id="blue">
<a href="/vote.php?color=blue" class='vote'><img src="images/blue.jpg" width="100%" /></a>
</div>

<div id="green">
<a href="/vote.php?color=green" class='vote'><img src="images/green.jpg" width="100%" /></a>
</div>

Javascript / jquery:

$('.vote').click(function() {
    $.ajax({
        type: 'POST',
        url: $(this).attr('href'),
        cache: false,
        success: function(resp){

        }
    });
    return false;
});

Upvotes: 1

Yarek T
Yarek T

Reputation: 9925

  1. attach a click handler to each of the anchors
  2. in your ajax request send the id of the parent div as a post parameter
  3. Once the request is complete, update the corresponding div with the count from the result

Upvotes: 1

Nick Mitchinson
Nick Mitchinson

Reputation: 5480

HTML:

<div id="red" data-color="red" class="answer">
    ...
</div>
<div id="blue" data-color="green" class="answer">
    ...
</div>
<div id="green" data-color="blue" class="answer">
    ...
</div>

JS:

$('.answer').click ( function (e) {
    var color = $(this).attr("data-color");
    $.ajax({
        url: '/your/relative/endpoint',
        type: 'POST',
        data: '{ color: "'+color+'" }',
        success: function (res) {
            ...
        },
        error: function (jqXHR) {
            ...
        }
    })
})

This will track each color and make the request to your server on click with the appropriate color. Remember that you should sanitize the input server side.

Upvotes: 3

Related Questions