0

I successfully fetch the data from the database. The problem is that, I want to display the results using Ajax request. The results/Output which displayed twice, I mean the *first output which displayed through Ajax (@the bottom of index.php), and the Second output displayed through PHP ECHO (**@**the bottom of the page). What can I do to get a single output through Ajax without adding another file and without refreshing the page?

index.php

<head> 
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="javas.js"></script>
</head>
<body>
         <div id="table_content"></div>
<?php 
include ("db.php"); 
error_reporting(~E_NOTICE);

function ShowForm($AnswerCommentId) {   
        echo '<form id="myForm">';  
        echo '<input id="user" name="user" />';                 
        echo '<textarea id="text" name="text"></textarea>';     
        echo sprintf('<input id="ParentId" name="ParentId" type="hidden" value="%s"/>', ($AnswerCommentId));
        echo '<button type="button" OnClick=SendComment()>Comment</button>';
        echo '</form>';
}

$query="SELECT * FROM `comm` 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;
        foreach($treeArray as $item){
            if ($item[1] == $pid){  
                         echo sprintf('<div class="CommentWithReplyDiv" style="margin-left:%spx;">',$level*60);     
                                        echo sprintf('<p>%s</p>', $item[2]); 
                                        echo sprintf('<div>%s</div>', $item[3]);  
                  if ($level<=2) echo sprintf('<a href=""  onclick="AnswerComment(%s);return false;">Reply</a>', $item[0]);
                  if ($AnswerId == $item[0]) echo sprintf('<div id="InnerDiv">%s</div>', ShowForm($AnswerId));
                         echo '</div><br/>';
              tree($treeArray, $level+1, $item[0]); // Recursion
            }       
        }
}
    tree($mytable,0,0); 
?>
    <a href="" id="Link">Comment</a>
    <div id="MainAnswerForm" style="display:none;width:40%; margin:0 auto;"><?php ShowForm(0); ?></div>
    <div id="AfterMainAnswerForm"></div>
<script>
$(document).ready(function(){   
    $("#Link").click(function () {
        $("#InnerDiv").remove();
        $("#MainAnswerForm").slideToggle("normal");
        return false;
    });
});
</script>
</body>

Page.php

<?php
include ("db.php"); 
$user = $_POST['user'];
$text = $_POST['text'];
$ParentId = $_POST['ParentId'];
$action = $_POST['action'];

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

Javas.js

        function show_messages(){
        $.ajax({
            url: "index.php",
            cache: false,
            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: "page.php",                    
            data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",        
            success: function(html){ 
                show_messages(); 
            }            
    });
    return false;
    }
Vena
  • 33
  • 5
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky May 31 '17 at 17:30

1 Answers1

0

OK I think its more simple than you think

while you're using .html() it should change all the content of your div but while you're using <div id="table_content"></div> then the <?php ?> your code will show both - one appended to the div and under it the one which echoed by php ... so instead of using

<div id="table_content"></div> 
<?php ?>

just wrap the <?php ?> inside the div

<div id="table_content">
<?php ?>
</div>

Alternative way: by using jquery wrapAll() but while Id must be unique you'll need to .remove() the #table_content element first then wrap all your code inside a new #table_content div .. see the example below

$(document).ready(function(){
  $('#table_content').remove();
  $('.CommentWithReplyDiv').wrapAll('<div id="table_content"></div>');
});
#table_content{
  margin : 50px;
  background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_content"></div>
<div class="CommentWithReplyDiv">1</div>
<div class="CommentWithReplyDiv">2</div>
<div class="CommentWithReplyDiv">3</div>
<div class="CommentWithReplyDiv">4</div>
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28