-1

I'm using below php PDO and ajax program to submit user comment on post. At first when I did this, it was work fine but now it stopped working what am I doing wrong can someone fix this for me or decide a better way to achieve it?

Problem Currently, when I submit reply it will post to my database but it will not return back the message from server. Example: when I post "hello" I expect it to instantly show it without reloading page.

Here is AJAX

<script>
$(document).ready(function(){
    $('#add-comment').submit(function()
    {
        var comment = $('#comment').val();
        var name = $('#anony').val();
        var rid = $('#rid').val();

        $('#response-out').html("<i class='fa fa-spinner fa-spin' style='font-size:19px;'></i>");
        $.ajax({
            type: 'POST',
            url: '/alter_reply.php', 
            data: 'comment='+comment+'&name='+name+'&rid='+rid,
        })
        .done(function(data){

            $('#response-out').html(data);

        })
        .fail(function() {

            alert( "Posting failed." );

        });
        return false;

    });
});
</script>

alter_reply.php

<?php

if($_POST){
$db_host = "localhost";
$db_user = "root";
$db_pass = "pass";
$db_name = "cods";

     try {
     $db_conn = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
     $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $stmt = $db_conn->prepare("INSERT INTO replys(rid,mesreplys,rtime,rusername) VALUES(:rid,:mesreplys,:rtime,:rusername)");


$stmt->bindParam(':rid', $rid); 
$stmt->bindParam(':mesreplys', $comment);
$stmt->bindParam(':rtime', $timedate); 
$stmt->bindParam(':rusername', $user); 



$form = $_POST;
$rid = mysql_real_escape_string($form['rid']);
$comment = mysql_real_escape_string($form['comment']);
$timedate = date("Y-m-d H:i:s");
if(isset($_SESSION['username'])){
$user = $_SESSION['username'];
}else{
$anony_user = mysql_real_escape_string($form['name']);
$user = $anony_user;    
}


    $stmt->execute();

//I don't know how to do it again that why i echo back the submitted values
//if you can do it more better for me i will appricite
echo "<td><table>
                <tbody>
                    <tr>
                        <td class='comment-score'>
                                &nbsp;&nbsp;
                        </td>
                        <td>
                                &nbsp;
                        </td>
                    </tr>
                </tbody>
            </table>
        </td>";
     echo  "<td class='comment-text'>
            <div style='display: block;' class='comment-body'>";
                echo "<span class='comment-copy'>";
                echo "$comment"; 
                echo "</span> <a href='' class='comment-user'>";
                echo "$user"; 
                echo "</a> <span class='comment-date' dir='ltr'> @<a class='comment-link' href='#'><span title='' class='relativetime-clean'>";
                echo "$timedate"; 
        echo "</span></a></span></div></td>";

    }
catch(PDOException $e)
    {
    echo "Error:" . $e->getMessage();
    }
$db_conn = null;
}
?>

here is HTML

<div id="response-out" class='comment'> </div>
<form id="add-comment" action="javascript:void(0);" style="font-size: 100%;">

<textarea placeholder="" name="comment" cols="68" rows="3" style="min-height:30px;" id="comment" required="true"></textarea>
<br/>
<?php 
if(!isset($_SESSION['username'])) { 
echo "<label>Enter name</label><br>";
echo "<input placeholder='Enter a name' style='width:130px;height: inherit;' required='true' id='anony' type='text' name='name'/>";
}?>
<input tabindex="0" value="Add Comment" class="btnpostq" id="donedbtn" type="submit"/>
<input type="hidden" value="<?php echo $_GET['postid'];?>" name="rid" id="rid"/>
</form>
Ashan
  • 479
  • 7
  • 28
Codesoft
  • 99
  • 2
  • 10
  • Possible duplicate of [Can I mix MySQL APIs in PHP?](http://stackoverflow.com/questions/17498216/can-i-mix-mysql-apis-in-php) – Rajdeep Paul Jan 29 '16 at 09:53
  • See this: `$rid = mysql_real_escape_string($form['rid']);`, `$comment = mysql_real_escape_string($form['comment']);` and `$anony_user = mysql_real_escape_string($form['name']);`, you're mixing the APIs. – Rajdeep Paul Jan 29 '16 at 09:54
  • @RajdeepPaul also the same thing when i remove `mysql_real_escape_string` – Codesoft Jan 29 '16 at 09:58
  • You didn't start session anywhere in **alter_reply.php** page. Add this line `` at the very top of your php scripts. – Rajdeep Paul Jan 29 '16 at 10:03
  • I did start session it is posting well but i want it to echo the datas out without refreshing the page – Codesoft Jan 29 '16 at 10:06
  • But I can't see this statement `session_start();` anywhere in **alter_reply.php** page. Anyway, if you think you did everything correct and just want *to echo the datas out without refreshing the page* then use [`event.preventDefault()`](https://api.jquery.com/event.preventdefault/) to prevent the form from being submitted in the first place. – Rajdeep Paul Jan 29 '16 at 10:13

2 Answers2

0

First : please check your php error are displayed. Then, I suppose you are using are debugger like FireBug to check your javascript and AJAX request. If not, configure php error and install a debugger for your browser. If yes, please confirm you have no JS error nor PHP error returne by AJAX.

The purpose of my answer is to first clean your code and try to avoid errors.

Javascript :

<script>
$(document).ready(function(){
    $('#add-comment').submit(function()
    {
        var comment = $('#comment').val();        
        var rid = $('#rid').val();

        // Check if anony exist to avoid JS error
        if(0 < $('#anony').length)
        {
            var name = $('#anony').val();
            var dataToSend = 'comment='+comment+'&rid='+rid;
        }
        else
        {
            var name = '';
            var dataToSend = 'comment='+comment+'&rid='+rid;
        }

        var dataToSend = 

        $('#response-out').html("<i class='fa fa-spinner fa-spin' style='font-size:19px;'></i>");
        $.ajax({
            type: 'POST',
            url: '/alter_reply.php', 
            data: dataToSend,
        })
        .done(function(data){

            $('#response-out').html(data);

        })
        .fail(function() {

            alert( "Posting failed." );

        });
        return false;

    });
});
</script>

PHP :

if(0 < sizeof($_POST))
{
    //First retrieve your data
    $form = $_POST;
    $rid = $form['rid'];
    $comment = $form['comment'];
    $timedate = date("Y-m-d H:i:s");
    if(isset($_SESSION['username'])){
        $user = $_SESSION['username'];
    }else{
        $anony_user = $form['name'];
        $user = $anony_user;    
    }

    $db_host = "localhost";
    $db_user = "root";
    $db_pass = "pass";
    $db_name = "cods";

    try 
    {
        $db_conn = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
        $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $db_conn->prepare("INSERT INTO replys(rid,mesreplys,rtime,rusername) VALUES(:rid,:mesreplys,:rtime,:rusername)");

        //Now you have first retrieve data, you can bind
        $stmt->bindParam(':rid', $rid); 
        $stmt->bindParam(':mesreplys', $comment);
        $stmt->bindParam(':rtime', $timedate); 
        $stmt->bindParam(':rusername', $user); 
        $stmt->execute();
    }
    catch(PDOException $e)
    {
        echo "Error:" . $e->getMessage();
    }
    $db_conn = null;

    //I don't know how to do it again that why i echo back the submitted values
    //if you can do it more better for me i will appricite

    //Cleaning HTML : your tags where crossing and you were including spans in spans, not sure its usefull

    echo 
            '<table>'.
                '<tbody>'.
                    '<tr>'.
                        '<td class="comment-score">'.
                                '&nbsp;&nbsp;'.
                        '</td>'.
                        '<td>'.
                                '&nbsp;'.
                        '</td>'.
                    '</tr>'.
                    '<tr>'.
                        '<td class="comment-text">'.
                            '<div style="display: block;" class="comment-body">'.
                                '<span class="comment-copy">'.$comment.'</span>'.
                                '<a href="" class="comment-user">'.$user.'</a>'.
                                '<span class="comment-date" dir="ltr">'.
                                    '@<a class="comment-link relativetime-clean" href="#">'.$timedate.'</a>'.
                                '</span>'.
                            '</div>'.
                        '</td>'.
                    '</tr>'.
                '</tbody>'.
            '</table>';


}
else
{
    echo 'no data';
}
ThinkTank
  • 1,187
  • 9
  • 15
0

I have finally found a solution to my problem here is what i did and is working fine

$(document).ready(function(e){
    $("#add-comment").submit(function(){
                var comment = $('#comment').val();
                var name = $('#anony').val();
                var rid = $('#rid').val();
    $.ajax({
    url:'/alter_reply.php',
    data:'comment='+comment+'&name='+name+'&rid='+rid,
    type: "POST",
    beforeSend: function(){
    $('#response-out').html("<i class='fa fa-spinner fa-spin' style='font-size:19px;'></i>");
    },
    success: function(data){
        $('#response-out').html(data);
    }
      });
   });
});
Codesoft
  • 99
  • 2
  • 10