PHP Poll with Results on Same Page

拈花ヽ惹草 提交于 2020-01-30 12:06:26

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18488881/php-poll-with-results-on-same-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!