How to create a simple vote by ajax in CakePHP 2.0
-
29-10-2019 - |
Question
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.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow