使用ajax和php在帖子上评论系统

时间:2016-06-22 05:16:43

标签: php ajax forms

这是我的代码,我将comment和post id(隐藏的输入标记)传递给另一个php文件comments.php,该文件应该将其插入db并显示结果但不会发生。< / p>

这是我的表单 - 在echo中引用的代码的一部分...我有一个与每个帖子相关联的自动增量pid,因此对于每条评论,commentpid都是存储在数据库中:

<form  method=\"POST\" onSubmit=\"comment(); return false;\">
    <input  id=\"comment\" type=\"text\" placeholder=\"Add Comment...\" name=\"comment\">
    <input type=\"hidden\" name=\"pid\" value=\"".$row['pid']."\">
    <div class=\"z\"><input type=\"submit\" name=\"submit\" ></div>
</form>

JavaScript - 使用comment()为每个帖子的评论表单调用函数onsubmit

function comment() {
    jQuery.ajax({
        url: "comments.php",
        data: $('form').serialize(),
        type: "POST",
        success:function(data){
            $("#".$row['pid']).html(data);
        },
        error:function (){
        }
    });
}

这是comments.php代码:

<?php
    session_start();
    include 'db.php';

    $j =$_POST['comment'];
    $k = $_POST['pid'];
    $l =$_SESSION['uname'];

    $sql = "INSERT INTO comments (pid,name,comment) values     ('$k','$l','$j')";
    $r = $conn->prepare($sql);
    $r->execute();
    if($r) {
        echo '<div class="comment">
                  <a class="avatar">
                      <img style="height:30px;"src="zmf.jpg">
                  </a>
                  <div class="content">
                      <a class="author">'.$l.'</a>
                      <div class="metadata">
                          <span class="date">Today at 5:42PM</span>
                      </div>
                      <div class="text">';
                          echo   $j.'</div>
                      <div class="actions">

                      </div>
                  </div>
              </div>
          ';
  }
?>

comments.php应该返回的内容会显示在div index.php中,id = #postid的{​​{1}}已经在每个帖子的index.php中分配了<div id=\"".$row['pid']."\"> </div>

index.php

div每个帖子都有div个帖子,因此发表评论的帖子会在每个帖子下方 $q = $conn->prepare("SELECT * FROM posts ORDER BY pid DESC"); $q->execute(); while($row = $q->fetch(PDO::FETCH_ASSOC)) { #my post in div #comment form <form method=\"POST\" onsubmit=\"comment()\"> <input id=\"comment\" type=\"text\" placeholder=\"Add Comment...\" name=\"comment\"> <input type=\"hidden\" name=\"pid\" value=\"".$row['pid']."\"> <div class=\"z\"><input type=\"submit\" name=\"submit\" ></div> </form> #div where recent comment is shown using ajax <div id=\"".$row['pid']."\"> </div> #nested while loop for comments $zmf = "SELECT * FROM comments WHERE pid = '" . $row['pid'] . "' ORDER BY comid DESC"; $zed = $conn->prepare($zmf); $zed->execute(); $run = $zed->fetch(); while($run = $zed->fetch()) { my div code and all..for comments } } 显示评论。任何帮助将不胜感激。

我运行两个while循环来显示每个帖子的所有previuos评论。 第一个循环显示post和一个嵌套的while循环,每个帖子显示每个帖子的注释...以及while循环中每个帖子的注释表单以及一个id = postid的div来显示ajax结果..

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import re
import sys
import time
import subprocess
import prettytable
from progress import *
global kill
global stop
p = progress_bar_loading()

class gmond_class:

   chkMinionUp      = ''
   chkMinionUpRes   = ''
   chkMinionDown    = ''
   chkMinionDownRes = ''
   gmondChkMinion   = ''
   gmondMinionRes   = ''
   replaceHyfen     = ''
   splitStr         = ''
   verifyService    = ''
   chkMinionOut     = ''
   minion           = ''
   checkError       = ''
   checkService     = ''
   checkGm          = ''
   onchange         = ''
   gmd              = ''
   final            = ''
   code             = ''
   cmdMinion        = ''
   removeItem       = ''
   max_value        = 10
   alive            = ''

   def displayMinionUp(self):
       self.kill = False
       self.stop = False
       print type(self.kill)
       p.start()
       try:
           self.alive = self.getMinionUp()
           if self.alive !='':
              time.sleep(1)
              self.stop = True
       except KeyboardInterrupt or EOFError:
           kill = True
           stop = True

   def getMinionUp(self):
       self.chkMinionUp    = subprocess.Popen("salt-run manage.up | wc -l", shell = True, stdout=subprocess.PIPE)
       self.chkMinionUpRes = self.chkMinionUp.communicate()[0].rstrip()
       if len(self.chkMinionUpRes) > 0:
          self.printBlank()
          return str(self.chkMinionUpRes)
       else:
          return 0


class file progress.py

#!/usr/bin/python

import sys
import time
import threading

class progress_bar_loading(threading.Thread):

    def run(self):
        global stop
        global kill
        print 'Loading....  ',
        sys.stdout.flush()
        i = 0
        while stop != True:
            if (i%4) == 0:
               sys.stdout.write('\b/')
            elif (i%4) == 1:
                 sys.stdout.write('\b-')
            elif (i%4) == 2:
                 sys.stdout.write('\b\\')
            elif (i%4) == 3:
                 sys.stdout.write('\b|')

                 sys.stdout.flush()
                 time.sleep(0.2)
                 i+=1

        if kill == True:
           print '\b\b\b\b ABORT!',
        else:
           print '\b\b done!',


Error Message :

[root@vmsalt-master test]# python check_gmond_config.py 

<type 'bool'>
Loading....  Exception in thread Thread-1:
Traceback (most recent call last):File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner self.run()
File "/root/python-salt/test/progress.py", line 14, in run while stop != True:
NameError: global name 'stop' is not defined

每个帖子都有一个id pid .. 但它的工作..plz帮助

1 个答案:

答案 0 :(得分:2)

页面上有多个<form>元素吗?如果是,请尝试将$('form').serialize()更改为$(this).serialize()

您能提供一些关于您获得的结果的更多信息吗?你在数据库中看到任何条目吗?在ajax请求之后,你在div中看到的输出是什么?

您使用的是PDO吗?在if($r)检查中添加其他条件,然后添加print_r($r->errorInfo())。尝试启用Firefox中Chrome / Firebug中的开发人员工具面板,并检查ajax(XHR)请求的结果。如果sql查询失败,则可能会引发PDOException。确保XHR请求返回200 OK http状态。

尝试以下代码并发布输出

<?php
session_start();
include 'db.php';

$j = $_POST['comment'];
$k = $_POST['pid'];
$l = $_SESSION['uname'];

$sql = "INSERT INTO comments (pid,name,comment) values     ('$k','$l','$j')";

print_r($_POST);

try {
    $r = $conn->prepare($sql);
    $r->execute();
    if ($r) {
        echo '<div class="comment">
                    <a class="avatar">
                        <img style="height:30px;"src="zmf.jpg">
                    </a>
                    <div class="content">
                        <a class="author">' . $l . '</a>
                        <div class="metadata">
                            <span class="date">Today at 5:42PM</span>
                        </div>
                        <div class="text">' . $j . '</div>
                        <div class="actions">

                        </div>
                    </div>
                </div>
            ';
    } else {
        print_r($r->errorInfo());
    }
} catch (\Exception $e) {
    print_r($e);
}