Post a comment and view follow without refreshment

5

Updated 5

Good morning, I'm trying to create a comment system that is equal to link

>

Here is the JavaScript code to send everything to PHP:

$(function() {
    $('.commentform').submit(function() {
    var comment_publication_id = $(this).find('input[name=comment_publication_id]').val();
    var comment = $(this).find('textarea[name=comment]').val();
    var dataString = 'comment=' + comment + '&comment_publication_id=' + comment_publication_id;
    var divtoload = '#commentsforpublication' + comment_publication_id;
    var sendcommentbutton = $(this).find('button[type=submit]');
    var commenttextarea = $(this).find('textarea[name=comment]');
    if (comment == ""){
    alert("Não pode deixar em branco!");
    } else
    $.ajax({
      type: "POST",
      url: "sendcomment.php",
      data: dataString,
      dataType: 'json',
      cache: false,
      success: function(mydata) {
      $(sendcommentbutton).attr("disabled", true);
      $(commenttextarea).attr("disabled", true);
      $("#" + comment_publication_id + ".commentform").prepend('<div id="loading"><img src="/img/ajax-loader.gif" align="absmiddle"></div>');
      $("textarea#commentto" + comment_publication_id).val('');
      setTimeout(function(){
      $("#loading").remove();
      var addcomment = '<div> "Exemplo, coloca mydata.nome do array que está no php " </div>';
      $(divtoload).append(addcomment);
      $(divtoload).find(".commentbox:last").hide().fadeIn('slow').slideDown("normal");
      $(sendcommentbutton).attr("disabled", false);
      $(commenttextarea).attr("disabled", false);
      }, 4000);
      }
    });
return false;
  });
});

sendcomment.php (Here I do the INSERT and return values for JavaScript):

mysqli_query($conexao,"INSERT INTO questioncomments (comment_question_id,comment_autor_id,comment,comment_datetime) VALUES ('$comment_question_id','$comment_autor_id','$comment',NOW())");

$last_insert_id = mysqli_insert_id($conexao);

$questioncomments = "SELECT questioncomments.*, login.* FROM questioncomments INNER JOIN login ON questioncomments.comment_autor_id = login.user_id WHERE comment_id = $last_insert_id LIMIT 1";
$commentsresult = $conexao->query($questioncomments);
while ($rowcomments = $commentsresult->fetch_assoc()) {
$nome = $rowcomments["Nome"];   
$comment_question_id = $rowcomments["comment_question_id"];
$commentdatetime = date('d/m/Y \à\s H:i', strtotime($rowcomments["comment_datetime"])); 
}

//  array
$my = array(

 'comment_id'=>$last_insert_id,
 'user_id'=>$comment_autor_id,
 'Nome'=>$nome,
 'comment_date_time'=>$commentdatetime

);

// converto ele com a função json_encode

    $myJSON = json_encode($my);

// coloco na tela o objeto javascript

    echo($myJSON);

Form to submit comment:

<form method="post" class="commentform" id=" (Aqui é a ID da publicação) ">  
  <input type="text" name="comment" id="comment" class="sendcomment">
  <input type="hidden" name="comment_question_id" id="comment_question_id" value=" (Aqui é a ID da publicação) ">  
  <button type="submit" class="sendcomment-button">Enviar comentário</button>
</form>
    
asked by anonymous 05.05.2015 / 21:42

3 answers

4

I'll give you an example - a superficial explanation to get the idea across. Basically you have a DIV-PAI to encompass the comments. When submitting the form via AJAX , simply create the formatted element at startup using prepend using the comment ID as a reference for removal.

  
comment 3

comment 2 kbd>

Insert

$(function(){
    $('.commentform').submit(function(){
        $.ajax({
            type   : 'POST',
            url    : 'comment.php',
            data   : data,
            success: function( ID )
            {
                $('#content').prepend( '
                <div id="IDComment_' + ID + '">
                    <p>' + $( '#comment' ).val() + '</p>
                    <button id="delete" class="' + ID + '">deletar</button>
                </div>' )
            }
        });
    });
});

The insert sends the data and receives the comment ID for creating the element with the remove button and the comment text. Using prepend the comment submitted appears at the top of the DIV-FAT .

Delete

$(function(){
    $('#delete').click(function(){
        $.ajax({
            type   : 'POST',
            url    : 'comment.php',
            data   : data,
            success: function( $(this).attr('class') )
            {
                $('#IDComment_' + $(this).attr('class')).remove()
            }
        });
    });
});

The <

Considerations ...

This is a simple example, basically just the idea. Making js create and format HTML decreases the amount of data traffic. On the other hand you have in js elements that are part of a view , which ends up making it redundant. You can format the comment block in PHP and send it as json. Home case is a case.

I removed the variables from js to leave the code smaller, I believe this step is not a mystery.

    
06.05.2015 / 06:48
4

I find it interesting that you do not assign the comment code in the form. It would be interesting if you took the block. Take a look at the example below:

$(function() {
  $('.commentform').submit(function() {
    var data = $('.commentform').serialize();

    $.ajax({
      type: "POST",
      url: "sendcomment.php",
      data: data,
      success: function() {
        var tab = document.getElementById("table");
        var novoComentario = document.createElement("td");
        novoComentario.textContent = "Teste de comentario";
        tab.appendChild(novoComentario);
      }
    });
  });
});
<form method='post' action='#' class='commentform' id='commentquestion$question_id'>
  <input type='text' name='comment' class='sendcomment' required></input>
  <button type='submit' class='sendcomment-button'>Enviar comentário</button>
</form>

<table id="table">
  <tr>
    <td>Comentário 1</td>
    <td>Comentário 2</td>
    <td>Comentário 3</td>
  </tr>
</table>
    
05.05.2015 / 22:35
3

This is very simple to do in ajax. I'll give an example on which to base:

link

First you use jQuery to send the data to a php, this same php you save in the database and already a echo at the end of it with the information you need. Note that in the example I passed you have the variable data , it receives the return of this echo of your php.

Now, let's say you want to display what you have in the data variable (which is the return of your php, that is echo you gave there) to input . It's simple, just change the alert(data) you have in the example code to something like this:

$('#id_do_seu_input').val(data)

You will be saving in the bank and displaying without refresh of the page. Of course, the example in question just sends to php and receives the return, in php you will have to do the whole save scheme in a database, which I believe you know how to do.

If you have more problems let me know that I try to help otherwise.

    
05.05.2015 / 21:56