2016-08-16 3 views
1

Как я могу отобразить вывод из ajax и не отображать данные, используя php echo inorder, чтобы предотвратить дублирование одного и того же результата при обновлении страницы или при нажатии на ссылку ответа или удаления?Как показать данные с помощью ajax

вот мои коды

table_comments.sql

CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`idparent` int(5) unsigned NOT NULL DEFAULT "0", 
`user` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, 
`text` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, 
`date` datetime DEFAULT NULL, 
PRIMARY KEY (`id`) 
) 
ENGINE=MyISAM 
DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci 
AUTO_INCREMENT=1; 

action.php

<?php 
include ("db_connect.php"); 

// Get the variables from forms 
$user = $_REQUEST['user']; 
$text = $_REQUEST['text']; 
$comment_on = $_REQUEST['comment_on']; 
$ParentId = $_REQUEST['ParentId']; 
$action = $_REQUEST['action']; 

if ($action == "add") { 
    // Add data to the database  
    $query = "INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW(),'{$comment_on}')"; 
    $result = mysql_query($query); 
} 

if ($action == "delete") { 
    // Delete data from the database  
    $result = mysql_query("DELETE FROM `comments` WHERE id=$text"); 
} 
?> 

index.php

<?php header('Content-type: text/html; charset=utf-8') ?> 
<html> 
    <head> 
     <script type="text/javascript" src="jquery-1.11.2.min.js"></script> 
    </head> 
    <body> 

    <div id="table_content" >//Display result using ajax</div> 

    <script>  
     function show_messages() 
     { 
     $.ajax({ 
      url: "index.php", 
      cache: false, 
      success: function(html){ 
      $("#table_content").html(html); 
      } 
     }); 
     } 

     function clean_form() 
     { 
     $("#user").val('name'); 
     $("#text").val('comment'); 
     } 

     $(document).ready(function(){ 
     // show_messages(); 

     }); 
    </script> 

    <script> 
    function DeleteComment(number) // Function to remove comments with id = number 
    { 
     $.ajax({ 
     type: "POST", 
     url: "action.php",     
     data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",     
     success: function(html){       
      // show_messages();    
      } 
     }); 
    } 

    function AnswerComment (id) // Send the comment numbers , which correspond to 
    { 
     $.ajax({ 
     type: "POST", 
     url: "index.php",     
     data: "AnswerId="+id,     
     success: function(html){       
      $("#table_content").html(html);    
      } 
     });  
    } 

    function SendComment() // Send data from the form 
    { 
     var user1 = $("#user").val(); 
     var text1 = $("#text").val();  
     var ParentId1 = $("#ParentId").val() + ""; 
     if (user1 =='' || user1 =='name') 
     { 
     alert ("Enter your Username"); 
     return false; 
     } 
     if (text1 =='' || text1 =='comment') 
     { 
     alert ("Enter name to comment"); 
     return false; 
     } 

     $.ajax({ 
     type: "POST", 
     url: "action.php",     
     data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",   
     success: function(html){     
      // show_messages(); 
      // clean_form();  
      } 
     }); 
     return false; 
     } 
    </script> 

    <?php 
    function ShowForm($AnswerCommentId) // Form add a comment 
    { 
     ?> <br/> 
     <form id="myForm" action=""> 
     <input id="user" name="user" value="name" autocomplete="off" 
     onfocus="if(this.value == 'name'){this.value = ''}" 
     onblur="if(this.value == ''){this.value = 'name'}"/>     
     <br/><br/> 
     <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);?>"/> 
     <br/> 
     <button type='button' OnClick=SendComment()>Comment</button> 
     </form> 
     <br/> 
     <?php 
    } 

    include ("db_connect.php"); // Connect to the database 

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

    // Read the comment number to which the answer , if it exists 
    if (isset($_REQUEST['AnswerId'])) 
    { 
     $AnswerId = $_REQUEST['AnswerId'];  
    } 
    else 
    { 
     $AnswerId = 0; 
    } 

    // Read comments from the database and writing the array     
    $i=0; 
    while ($mytablerow = mysql_fetch_row($result)) 
    { 
     $mytable[$i] = $mytablerow; 
     $i++; 
    } 

    // Function for constructing a tree Comments 
    function tree($treeArray, $level, $pid = 0) { 
     global $AnswerId; 
     if (!$treeArray) { 
     return; 
     } 
     foreach ($treeArray as $item) { 
     if ($item[1] == $pid) { 
      ?>  
       <!-- Showing each comment with the correct indentation --> 
       <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) { // Limit nesting level 
      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 
      // Display the form for an answer, if the answer Comment 
      if ($AnswerId == $item[0]) { 
      ?><div id="InnerDiv"><?php 
      ShowForm($AnswerId); 
      ?></div><?php 
      } 
      ?> </div> <?php 
      echo ('<br/>'); 
      tree($treeArray, $level + 1, $item[0]); // Recursion 
     } 
     } 
    } 

    tree($mytable, 0); 
    ?> 

    <!-- Reply form at the bottom of the page--> 
    <br/> 
    <a href="" id="LeaveCommentLink">leave a comment</a> 
    <div id="MainAnswerForm" style="display:none;"> 
     <?php 
     ShowForm(0); 
     ?> 
    </div> 
    <div id="AfterMainAnswerForm"></div> 

    <script> 
    // The emergence reply form at the bottom of the page when you click on the link 
    $(document).ready(function(){ 
     $("#LeaveCommentLink").click(function() { 
     $("#InnerDiv").remove(); 
     $("#MainAnswerForm").slideToggle("normal"); 
     return false; 
     }); 
    }); 
    </script> 

    </body> 
</html> 

ответ

0

Пожалуйста, отдельный доступ к базе данных, бизнес-логику и уровень просмотра, а также код JavaScript и разметку HTML. Вы ввели целый вывод index.php в свой show_messages() метод, включая JavaScript и <body> (что, вероятно, является причиной дублирования записей)! Напишите отдельный файл, который просто возвращает комментарии в HTML и использует его в вызове AJAX.

+0

Спасибо за советы, он отлично работает, если я создал другой файл, чтобы показать комментарии. Но, моя проблема в том, что когда я пытаюсь создать один php-файл, который будет включать ajax и php-коды, поэтому он может упростить мою работу, когда я хочу включить файл comment.php на разные страницы, чтобы он мог отображать комментарии к странице , Как я могу это сделать? – enance

+0

Так же, как вы делали с 'db_connect.php': избыточный код Refactor в свой собственный файл и' include' или даже 'require' it (require будет терпеть неудачу, если файл отсутствует, а include будет только предупреждать). Код будет выполнен, как если бы он был скопирован в эту точную точку. Вы также можете посмотреть в такие рамки, как Symfony или Zend, потому что делать все с нуля не в стиле с 1999 года. – YetiCGN

+0

Здравствуйте, я снова. Я хочу отобразить «index.php» с использованием JSON-кодирования, как я могу сделать, чтобы показать данные с переменной JSON и aJax? – enance

Смежные вопросы