How to create a simple vote by ajax in CakePHP 2.0

2.1k views Asked by At

I am just trying to create a simple vote with CakePHP 2.0 and Ajax. I am a newbie in this framework so i find it really difficult...

I just want to create a link with a vote action which will call an action in a controller to update the field "numberVotes" in a table of the Database.

I am trying it but i dont know if i am doing it well. I have this now:

//posts/view.ctp $this->Html->script('votar', array('inline' => false)); //it loads it on the layout

echo '<div id=\'vote\'>';
    echo $this->element('vote', array('id' => $post['Post']['id']));
echo '</div>'

Elements/vote.ctp

if(!empty($voting)){
echo "You have voted!!!";   
}else{
echo '<a href="#" onclick="votar(\''.$id.'\');return false;">Vote here!!</a>
}

webroot/js/vote.js

//XMLHttpRequest  Ajax
function newAjax()
{ 
var xmlhttp=false; 
try 
{ 
    xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
}
catch(e)
{ 
    try
    { 
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    catch(E) { xmlhttp=false; }
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest();     } 
return xmlhttp; 
}


function voting(num) {
var url;
var obCon = document.getElementById('vote');
var ajax = newAjax();

url = 'http://localhost:8888/mysite/posts/voting/' + num;
alert(url);
ajax.open("GET", url);  

ajax.onreadystatechange=function(){
    if(ajax.readyState==4){
        if(ajax.status==200){
            obCon.innerHTML=ajax.responseText;

        }else if(ajax.status==404){
            obCon.innerHTML = "Page not found";
        }else{
            obCon.innerHTML = "Error:"+ajax.status; 
        }
    }
}
ajax.send(null);

}

//Controllers/PostsController.php

public function voting($id = null){
            ... //stuff to add the vote in the DB
    $this->set(array('id' => $id, 'voting' => 'yes'));
    $this->render('/Elements/vote', false);
}

I am sure i am not using the power of CakePHP for ajax... but i dont know where i can apply it or how to do it. Any suggestion?

Thanks.

1

There are 1 answers

0
Lawson Kurtz On BEST ANSWER

It's not entirely clear to me how exactly you want this voting system set up, but here are some examples to get you headed in the right direction:

Use CakePHP's JS helper to setup the whole AJAX request.

We'll bind the AJAX request to the click event of a link with the id 'link-id'. This request will make its way through to your controller like a normal request, but will (well, it should) use Cake's default AJAX layout meaning that the result of the request should be just a hunk of html that we will use to replace everything in the #content div.

This goes in the view file:

<?php
$this->Js->get('#link-id');
$this->Js->event(
    'click',
    $this->Js->request(
        array('action' => 'vote', $post_id), //this is effectively www.yourdomain.com/posts/vote/1 (if the post_id is 1)
        array('async' => true, 'update' => '#content')
    )
);
?>

Your controller should then look something like this:

<?php
function vote($id) {
    //update your number in the database
    if(/* the update was a success */){
        $this->set('message', 'Thank you for voting!');
    } else {
        $this->set('message', 'Try again.');
    }

    //then in vote.ctp, echo $message somewhere
    //the result of vote.ctp will replace #content on your page
}
?>