计算一个按钮的点击次数,将其保存到MYSQL,然后显示当前值(AJAX,PHP)


Count clicks on one button, save it to MYSQL and then display the current value (AJAX, PHP)

这就是我想在 http://geheimprojekt.nomachines.org/上完成的目标

  1. 用户点击"Nochmal!按钮(生成新单词组合)
  2. 将点击发送到我的MySQL数据库(无需重新加载页面),将"点击"行增加1
  3. 更新段落中的文本"到目前为止已生成 n 个单词组合"。

这是我第一次尝试使用 AJAX。我有jQuery知识,但我无法连接它看起来的点。

该 SQL

CREATE TABLE IF NOT EXISTS `sggcount` (
  `counter` bigint(20) NOT NULL DEFAULT '2'
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german2_ci;
--
-- Dumping data for table `sggcount`
--
INSERT INTO `sggcount` (`counter`) VALUES
(2);

要让它工作非常简单。你需要一些 html 用于将来的div 你想在其中放置 couting:

<div id="counting"></counting>

然后在 generator() 函数的末尾添加以下内容:

function generator(){
    /*your code here...*/    
    var element = document.createElement("div");
    element.setAttribute("id", "result");
    element.appendChild(document.createTextNode(name));
    document.getElementById("placeholder").appendChild(element);
    /*the ajax code here*/
    var url='urltophpfile/phpfile.php';
    $.get(url,function(data){
        $('#counting').html(data+' Word combinations have been generated so far.');
    });
 }

现在在你的 phpfile.php 文件中,你将需要代码来增加计数。我想你知道怎么做这部分,如果现在我也可以帮助它。我将在此处添加一些示例代码,以便您有一个想法。

<?php
  mysql_connect('localhost', 'db-sgg', 'password') or die('Cannot connect to database server');
  mysql_select_db('db1152127-sgg') or die('Cannot select database');
  $databasecall = mysql_query("SELECT counter FROM sggcount WHERE counter > 1");
  /*so here you select the already stored value and then you make an update to increment it*/
  mysql_query("UPDATE sggcount SET counter=counter+1");
  $count = mysql_fetch_assoc($databasecall);
  echo $count['counter']+1;
?>

通过执行上面的 echo,您将返回递增的值,ajax 将显示它。

更新 1

添加了更全面的 php 代码

注意:如果您添加 jquery 脚本,请将生成器函数更改为使用 jquery。

使用 jQuery,您可以将点击事件绑定到您的按钮并发出 ajax 请求。

  • JQuery ajax doc

在服务器端,您的 PHP 页面应该更新 SQL 数据。遵循Javascript演示代码

$(document).ready(function(){
    $('button-selector').click(function(){
        //use jquery ajax call to call php server page that update SQL data
        $.ajax({
              url: "updateClick.php",
             context: document.body
             }).success(function() { 
                     //success callback
             });
    });
});

单击使用时发送 AJAX 请求:

$('#button').click(function(){ // when user `click` element with `id="button"` (#button)
 $.ajax({ // Start AJAX call
  url: 'accept.php', // URL to send AJAX request
  success: function(data) { // Function to execute on SUCCESS reply (reply data as paramenter)
    var cc = $('#clicks_count').html(); // In your element with `id="clicks_count"` you store your click count (`<a id="clicks_count">21</a>`). Assign to `cc` javascript variable value of clicls_count
    $('#clicks_count').html(cc + 1); // Increasing clicls_count on 1 and write it to `<a id="clicks_count">22</a>`
  }
});
});

接受时.php使用脚本将点击计数器增加 1。