There was a great article posted by CSS-Tricks.com describing how to create a poll using PHP and a MySQL database. I've followed this and created a nice poll for myself. I noticed in the comments a mentioning of using AJAX to show the results on the same page instead of a completely separate page.
I am wondering what is the best way to display PHP Poll results on the same page?
UPDATE:
The answer is really simple. In fact, CSS-Tricks' poll without AJAX in my opinion is more difficult since it requires a database. This one does not!
The complete tutorial for creating a poll with PHP and AJAX is can be viewed here:
http://www.w3schools.com/php/php_ajax_poll.asp
I just wanted to clarify how to set the arrays up for more than two poll options. First you get the "database" (i.e. text file, not MySql).
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
Then you put the data in an array:
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
//if multiple options
$array = explode("||", $content[0]);
$option1array = $array[0]; //note: these values can be text values also. If text value, nothing changes with this part of the code.
$option2array = $array[1];
$option3array = $array[2];
$option4array = $array[3];
Store Data in "database"
if ($vote == 'option1')
{
$option1array = $option1array + 1;
}
if ($vote == 'option2')
{
$option2array = $option2array + 1;
}
if ($vote == 'option3')
{
$option3array = $option3array + 1;
}
if ($vote == 'option4')
{
$option4array = $option4array + 1;
}
Then, output your results. For file structure and AJAX script, see the complete tutorial.
You have two options:
1) Use ajax just as you suggested in your question, when you submit the vote via ajax, get the results back as the response.
2) Get the results before the vote is submitted, it will still need to be submitted via ajax if you want to stay on the same page. But instead of using ajax to get back the results, since you have the results prior to the vote you could just add one vote to the appropriate selection choice, then use Javascript / CSS to change the results from hidden to displayed.
I've built a contest system where users submit tickets then one is randomly chosen to win, and now I'm trying to figure out a way to display to users the tickets they have already submitted. Each ticket has an id, a date, and an invoicenumber. I want to display all the invoice numbers that a user has submitted so far.
Here is the method I have in my methods page. (I've organized my methods into one php file and then i just call them when needed.)
function GetSubmittedBallots()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT invoicenumber FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['invoicenumber'];
}
}
and then on my html page that I want it to echo on, i just call it
<?php GetSubmittedBallots(); ?>
Sadly, this doesn't work. So my question is, how would i go about displaying the $row array on my html page?
<?php
require("methods.php"); // Include the file which has the "GetSubmittedBallots" function or method, if it's in a separate file
GetSubmittedBallots(); // Run the function / method
?>
If this doesn't work, please let us know any errors you receive.
Does it echo "Array"?
That's because you are trying to echo an array.
You should use something like print_r or var_dump, given that you are just trying to access the queried results. In my opinion the method should build a multidimensional array with the records, and then the template logic should loop through them and echo the values in a nice way. Be it a table or nicely arranged HTML.
If I'm not wrong, $this keyword is indicating you're in a class? If so, you need first to init that class and try to call GetSubmittedBallots function after init;
// assuming that class's name is Users
$users = new Users();
$users->GetSubmittedBallots();
I have got a feature on my website called 'View friends' that displays a hidden div containing a users friends. The only problem so far is I would like it so that it would show 7 members on each row for 3 rows so a total of 21 members on each page. I know I will have to round up NumOfMembers/21 giving me the pages needed. I just need some advice in how I should set up the pagination from when thee SQL query gets the total amount of friends. Any ideas?
The SQL-query should use the limit and offset parameters for pagination, depending on the page n you are on, like this:
SELECT .... LIMIT 21 OFFSET n*21
When handling the results, simply use the modulo operator for determining the lines and rows your current result has to be put in:
// where $i is the result number
$row = $i % 7;
$line = $i % 3;
You have 2 options:
First you can load everything from the php in one query and put all users in an array(content), and just display in pages!
content = [];
max = 21;
function handlePaginationClick(page, pagination_container) {
$('#MyContentArea').empty();
for(var i=0;i<max;i++) {
if(null!=content[(page*max)+i]) $('#MyContentArea').append(content[(page*max)+i]);
}
return false;
}
$("#News-Pagination").pagination(content.length, {
items_per_page:max,
callback:handlePaginationClick
});
you can use Jquery Pagination: https://github.com/gbirke/jquery_pagination#readme
for that.
Another approach is still using jquery pagination, but not load everything at once! then you must have same ajax call in the method 'handlePaginationClick' to pull all page information.
Update, Solved:
After all this I found out that I was calling an old version of my code in the update ajax.
'boardControl.php' instead of 'boardUpdate.php' These are the kinds of mistakes that make programing fun.
I'm writing a browser gomoku game. I have the ajax statement that allows the player to play a piece.
$(document).ready(function() {
$("td").live('click',function(){
var value = $(this).attr('id');
$.get('includes/boardControl.php',{play: value, bid: bid});
});
});
value = board square location
bid = board ID
Before creating a user login for player identification, the server side php had a temporary solution. It would rotate the piece state for the squares when clicked instead of knowing what player to create them for.
After creating login stuff I set a session variable for the player's ID. I was hoping to read the session ID from the php during the ajax request and figure out what player they are from there.
session_start();
...
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
For some reason when I run the full web app, the pieces still cycle though, even after I deleted the code to make them cycle.
Furthermore, after logging in If i manually load the php page in the browser, it modifies the database correctly (where it only plays pieces belonging to that player) and outputs the correct results.
It seems to me that the session is not being carried over when used with Ajax. Yet Google searches tell me that, sessions do work with Ajax.
Update: I'm trying to provide more information.
Logging in works correctly. My
ID is recognized and I printed it
out next to the board to ensure that
I was retrieving it correctly.
The ajax request does update the
board. The values passed are
correct and confirmed with firebug's
console. However instead of placing
pieces only for the player they
belong to it cycles though the piece
states (0,1,2).
When manually browsing to
boardUpdate.php and putting in the
same values sent from the Ajax the
results seen in the echo'ed response
indicates that the corresponding
piece is played each time as
intended.
Same results on my laptop after
fresh load of firefox.
Manually browsing to
boardUpdate.php without logging in
before hand leave the board
unchanged (as intended when no user
is found in the session).
I've double checked the that
session_start() is on the php files
and double checked the session ID
variables.
Hope this extra information helps, i'm running out of ideas what to tell you. Should I load up the full code?
Update 2:
After checking the Ajax responce in fire-bug I realized that the 'play' request does not get a result, and the board is not updated till the next 'update'. I'm still looking into this but I'll post it here for you guys too.
boardUpdate.php
Notable places are:
Refresh Board(line6)
Place Piece(line20)
function boardUpdate($turnCount) (line63)
<?php
session_start();
require '../../omok/dbConnect.php';
//*** Refresh Board ***
if(isset($_GET['update']))
{
$bid = $_GET['bid'];
$Query=("SELECT turn FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
if($_GET['turnCount'] < $turnCount) //** Turn increased
{
boardUpdate($turnCount);
}
}
//*** Place Piece ***
if(isset($_GET['play'])) // turn order? player detect?
{
$squareID = $_GET['play'];
$bid = $_GET['bid'];
$Query=("SELECT turn, boardstate FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
$boardState=mysql_result($Result,0,"boardstate");
$turnCount++;
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
// if($newPiece != 0)
// {
$oldPiece = getBoardSpot($squareID, $bid);
$oldLetter = $boardState{floor($squareID/3)};
$slot = $squareID%3;
//***function updateCode($old, $new, $current, $slot)***
$newLetter = updateCode($oldPiece, $newPiece, $oldLetter, $slot);
$newLetter = value2Letter($newLetter);
$newBoard = substr_replace($boardState, $newLetter, floor($squareID/3), 1);
//** Update Query for boardstate & turn
$Query=("UPDATE board SET boardState = '$newBoard', turn = '$turnCount' WHERE bid = '$bid'");
mysql_query($Query);
// }
boardUpdate($turnCount);
}
function boardUpdate($turnCount)
{
$json = '{"turnCount":"'.$turnCount.'",'; //** turnCount **
$bid = $_GET['bid'];
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
$json.= '"boardState":"'.$Board.'"'; //** boardState **
$json.= '}';
echo $json;
}
function letter2Value($input)
{
if(ord($input) >= 48 && ord($input) <= 57)
return ord($input) - 48;
else
return ord($input) - 87;
}
function value2Letter($input)
{
if($input >= 10)
return chr($input += 87);
else
return chr($input += 48);
}
//*** UPDATE CODE *** updates an letter with a new peice change and returns result letter.
//***** $old : peice value before update
//***** $new : peice value after update
//***** $current : letterValue of code before update.
//***** $slot : which of the 3 sqaures the change needs to take place in.
function updateCode($old, $new, $current, $slot)
{
if($slot == 0)
{// echo $current,"+((",$new,"-",$old,")*9)";
return letter2Value($current)+(($new-$old)*9);
}
else if($slot == 1)
{// echo $current,"+((",$new,"-",$old,")*3)";
return letter2Value($current)+(($new-$old)*3);
}
else //slot == 2
{// echo $current,"+((",$new,"-",$old,")";
return letter2Value($current)+($new-$old);
}
}//updateCode()
//**** GETBOARDSPOT *** Returns the peice value at defined location on the board.
//****** 0 is first sqaure increment +1 in reading order (0-254).
function getBoardSpot($squareID, $bid)
{
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
if($squareID %3 == 2) //**3rd spot**
{
if( letter2Value($Board{floor($squareID/3)} ) % 3 == 0)
return 0;
else if( letter2Value($Board{floor($squareID/3)} ) % 3 == 1)
return 1;
else
return 2;
}
else if($squareID %3 == 0) //**1st spot**
{
if(letter2Value($Board{floor($squareID/3)} ) <= 8)
return 0;
else if(letter2Value($Board{floor($squareID/3)} ) >= 18)
return 2;
else
return 1;
}
else //**2nd spot**
{
return floor(letter2Value($Board{floor($squareID/3)}))/3%3;
}
}//end getBoardSpot()
?>
Please help, I'd be glad to provide more information if needed.
Thanks in advance =)
From the small snippet of code we have, it's difficult to tell what your problem might be. What I can say is that session_start should be one of the first things you do on each page where you're expecting to use the session. After that, I would just immediately do a var_dump of $_SESSION to see that the data is in there (put a die right after that). It is quite possible that your true problem lies somewhere else, and that the session is in fact working. Is there a problem with your login code, for example, that is causing it to wipe out the session?
You can use Firebug to look at the raw results of your AJAX calls, which should be helpful, since your script appears to work if you directly visit the page.
Cases where I've seen sessions not work as expected have generally been that session_start is being called too often or too late. The other possibility is that you have an insanely short timeout, but that sounds unlikely.
Finally, you can make sure that your PHP install is set to use cookie sessions. It's very unlikely at this point that it wouldn't be, but you could look.
One potential problem in this code is the use of $.get - it is cached by IE, so your server code doesn't run every time. Try using $.ajax with cache set to false:
$.ajax({
type: 'GET',
url: 'includes/boardControl.php',
cache: false,
data: {play: value, bid: bid}
});
Just happened to me, in my case was that i was importing a config file with the session_start and since i had deactivated errors i couldn't see that the import was never happening. Just triple check this, I know it's the basic.
I have a table (session) in a database which has almost 72,000 rows. I extract those rows with the help php+mysql but when the result is returned to the HTTPService, i need to wait for some 32 seconds before the all the rows start appearing in the DataGrid at once.
Question
Is there any way by which DataGrid may start displaying data one by one while the application may extract next rows in parallel. Or that the DataGrid may show data in chunks of hundreds. Like when application starts, it may show first 400 enteries in DataGrid, then the next 400 hundred are extracted until all the 72,000 rows are extracted?
Or can i involve threading such that one thread may be responsible for displaying data in datagrid while the other, executing in parallel may be responsible for extracting next data from database?
Thanks a lot guys as always.
<mx:HTTPService id="populateTable" url="request.php" method="POST" resultFormat="e4x">
<mx:request xmlns="">
<getResult>table</getResult>
</mx:request>
</mx:HTTPService>
code from PHP file
function populateTable()
{
$Result = mysql_query("SELECT * FROM session" );
$Return = "<Sessions>";
while ( $row = mysql_fetch_object( $Result ) )
{
$Return .= "<session><no>".$no."</no>" .
"<srcIP>".$row->srcIP."</srcIP>" .
"<dstIP>".$row->dstIP."</dstIP>" .
"<sPort>".$row->sPort."</sPort>" .
"<dPort>".$row->dPort."</dPort>" .
"<sessionID>".$row->sessionID."</sessionID>" .
"<numberOfConnections>".$row->numberOfConnections."</numberOfConnections>" .
"</session>";
}
$Return .= "</Sessions>";
// mysql_free_result( $Result );
echo $Return;
}
Consider redesigning the app. No sane user is gonna need to see the whole 72K of data at the same time.
Change the php script so that it accepts a startIndex parameter and selects 100 rows from that index instead of selecting *.
Add Next page/Previous page buttons in the flex app that causes HTTPService to be resend with changed startIndex value. Bind the lastResult of the HTTPService to the DataGrids dataProvider.
Update:
<mx:HTTPService id="service" resultFormat="e4x"/>
<mx:DataGrid dataProvider="{service.lastResult}">
<!-- columns -->
</mx:DataGrid>
<mx:Button label="Next" click="next()"/>
<mx:Button label="Prev" click="prev()"/>
<mx:Script>
<![CDATA[
private var currentIndex:Number = 0;
private var itemsPerPage:Number = 100;
private var total:Number = 72000;
private function next():void
{
if(currentIndex + 1 >= total/itemsPerPage)
return;
currentIndex++;
service.url = "request.php?page=" + currentIndex;
service.send();
}
private function prev():void
{
if(currentIndex == 0)
return;
currentIndex--;
service.url = "request.php?page" + currentIndex;
service.send();
}
]]>
</mx:Script>
Here I've appended the index to the url itself. You may also use the request property of HTTPService to send the data.
In php, change the query "SELECT * FROM session" so that it selects only 100 queries based on the value of $_GET["page"].