如何在同一页面上返回输出ajax php

时间:2017-03-10 15:04:24

标签: php ajax

我想组织从index.php到action的选择查询,因此我可以使用ajax调用该文件来显示页面上的数据。(index.php)。因此,我想要做的活动是能够将表单数据提交到数据库并在同一页面上显示结果(index.php)而无需刷新页面。请帮忙

Here's my files
1.action.php
2.index.php
3.maker.js

// ----------------------- action.php的------------------- ----------

<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];  

if ($action=="add")
{
    $query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
    $result = mysqli_query($conn,$query);
}

if ($action=="delete")
{   
    $delete = "DELETE FROM `comments` WHERE id=$text";
    $result = mysqli_query ($conn,$delete);
}
?>

//的index.php

<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId) 
{  ?> 
<form id="myForm">  
<input type="hidden"  name="comment_on" id="comment_on"  readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>               
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>       
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}

$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);

if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId'];    }
else
{ $AnswerId = 0; }

$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow; 
$i++;   
}

function tree($treeArray, $level, $pid = 0) 
{
global $AnswerId;

if (! $treeArray) 
{ return; } 

foreach($treeArray as $item){
    if ($item[1] == $pid)       
    {
        ?>  
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">    
        <div class="CommentDiv">
        <pre class="Message"><?php echo($item[3]) ; ?></pre>
        <div class="User"><?php echo($item[2]) ; ?></div>
        <div class="Date"><?php echo($item[4]) ; ?></div>
        <?php               
if ($level<=4)  { echo '<a href="" class="ReplyLink" onclick="AnswerComment('.$item[0].');return false;">Reply</a>'; }
         echo '<a href="" class="DeleteLink" onclick="DeleteComment('.$item[0].');return false;">Delete</a>';
        ?> </div> <?php

        if ($AnswerId == $item[0])
        {
        ?><div id="InnerDiv"><?php  ShowForm($AnswerId);  ?></div>
<?php   
        } 
        ?> </div> <?php 

        tree($treeArray, $level+1, $item[0]);   // Recursion
    }       
}
}
tree($mytable, 0);
?>

// maker.js

function DeleteComment(number){
$.ajax({
    type: "POST",
    url: "action.php",                  
    data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",                  
    success: function(html){                        
        $("#table_content").html(html);         
       }
 });
}

function AnswerComment (id){
$.ajax({
    type: "POST",
    url: "index.php",                   
    data: "AnswerId="+id,                   
    success: function(html){                        
        $("#table_content").html(html);             
       }
});     
}

function SendComment (){
var user1 = $("#user").val();
var text1  = $("#text").val();  
var ParentId1  = $("#ParentId").val() + ""; 
$.ajax({
    type: "POST",
    url: "action.php",  
    cache: false,       
    data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",        
    success: function(html){                
        $("#table_content").html(html); 
        clean_form();       
             }
});
return false;
}

1 个答案:

答案 0 :(得分:0)

所以你基本上是在尝试建立一个基于Ajax的评论系统,从我看来,你的代码组织并不是基于那里的任务,特别是你的index.php文件,所以这里是你可以做的简化事情:

  1. 你的action.php应该hanlde所有php数据库相关的任务
  2. 将您的html代码移动到其他文件(创建模板)
  3. 以下是我提出的修改后的代码(这仅供您参考,您应该根据需要修改此内容,并且正如Xorifelse在评论中建议的那样,出于安全考虑,您应始终在生产系统中使用预准备语句):

    <强> action.php的

    <?php
    
    include ("db_connect.php"); // Connecting to the database
    $action = $_REQUEST['action']; 
    
    if ($action=="add")
    {
        $user = $_REQUEST['user'];
        $text = $_REQUEST['text'];
        $ParentId = $_REQUEST['ParentId'];
    
    
        $query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
        $result = mysqli_query($conn,$query);
    }
    
    if ($action=="delete")
    {   
        $text = $_REQUEST['text'];
        $delete = "DELETE FROM `comments` WHERE id=$text";
        $result = mysqli_query ($conn,$delete);
    }
    
    if ($action=="get")
    {   
        $query="SELECT * FROM `comments` ORDER BY id ASC";
        $result = mysqli_query($conn,$query);
    
        if (isset($_REQUEST['AnswerId']))
        { $AnswerId = $_REQUEST['AnswerId'];    }
        else
        { $AnswerId = 0; }
    
        $i=0;
        $mytable = array();
        while ($mytablerow = mysqli_fetch_row($result))
        {
            $mytable[$i] = $mytablerow; 
            $i++;   
        }
    
        tree($mytable, 0, $AnswerId);
    }
    
    function tree($treeArray, $level, $ansId, $pid = 0) 
    {
        $AnswerId = $ansId;
    
        if (! $treeArray) 
        { return; } 
    
        foreach($treeArray as $item){
            if ($item[1] == $pid)       
            {
                include('comments.template.php');
                tree($treeArray, $level+1,$AnswerId, $item[0]);   // Recursion
            }       
        }
    }
    
    ?>
    

    <强>的index.php

    <html>
        <head>
            <title>Test page</title>
    
            <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
            <script type="text/javascript" src="maker.js"></script>
        </head>
        <body onload="loadComments();">
            <div id="table_content">
    
            </div>
        </body>
    </html>
    

    <强> comments.template.php

    <div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">    
    <div class="CommentDiv">
        <pre class="Message"><?php echo($item[3]) ; ?></pre>
        <div class="User"><?php echo($item[2]) ; ?></div>
        <div class="Date"><?php echo($item[4]) ; ?></div>
        <?php  
            if ($level<=4)  { 
                echo '<a href="javascript:" class="ReplyLink" onclick="AnswerComment('.$item[0].');">Reply</a>'; 
            }
            echo '<a href="javascript:" class="DeleteLink" onclick="DeleteComment('.$item[0].');">Delete</a>';
        ?> 
    </div> 
    
    <?php if ($AnswerId == $item[0]) { ?>
        <div id="InnerDiv"><?php  include('commentForm.template.php');  ?></div>
    <?php } ?> 
    

    <强> commentForm.template.php

    <form id="myForm">
        <input type="hidden"  name="comment_on" id="comment_on"  readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
        <input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>               
        <textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>       
        <input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
        <button type='button' OnClick="SendComment()">Comment</button>
    </form>
    

    <强> marker.js

    function DeleteComment(number){
        $.ajax({
            type: "POST",
            url: "action.php",                  
            data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",                  
            success: function(html){                        
                $("#table_content").html(html);  
                loadComments();       
            }
        });
    }
    
    function AnswerComment (id){
        $.ajax({
            type: "POST",
            url: "action.php",                   
            data: "AnswerId="+id+"&action=get",                   
            success: function(html){                        
                $("#table_content").html(html);             
            }
        });     
    }
    
    function SendComment (){
        var user1 = $("#user").val();
        var text1  = $("#text").val();  
        var ParentId1  = $("#ParentId").val() + ""; 
    
        $.ajax({
            type: "POST",
            url: "action.php",  
            cache: false,       
            data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",        
            success: function(html){                
                $("#table_content").html(html); 
                loadComments();       
            }
        });
        return false;
    }
    
    function loadComments (){
        $.ajax({
            type: "POST",
            url: "action.php",  
            cache: false,       
            data: "action=get",        
            success: function(html){                
                $("#table_content").html(html); 
                //clean_form();       
            }
        });
        return false;
    }