Post a comment and then display without refresh

Asked

Viewed 2,046 times

5

Updated 5

Good morning guys, I’m trying to create a comment system like http://demo.hazzardweb.net/comments/

below we have the javascript code that sends the form and then adds the comment, it is almost all right, missing modify something, because I have many forms with such id, as it does to send each form with each id?

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 the values to 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 send the 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>
  • Following what Anderson Nunes said is just you use Json, basically you will commit html to php using Jquery and make the comment go to php and the same gives a return to html and you populate an html element without giving refresh.

  • 1

    I edited all your question. Study the issue so as not to make the same mistakes in future questions, keep them well formatted.

  • 1

    Kevin, I have removed the excess bold and citations from your question, see Help Center and this thread http://meta.pt.stackoverflow.com/questions/1084/howwe shouldformatt-questions-answers how to format your questions and answers.

  • 1

    Thanks guys, for correcting me, I’m adapting to stackoverflow :)

  • I just think it would be interesting for you to keep the original question, the person enters the question, and sees in your answer the answer you adopted and does not understand the scope of your question...

  • One of the features you can(and should!) use is to select the best answer

  • sorry had forgotten to select, and I think the person who sees the question and understands the least of php, or at least has will, will search on how to send form with ajax, only this, because the question was practically based on it.

  • I reversed the last issue because you had removed the most important: the question! I recommend a [help] to better understand how the site works. The questions are not like a chat with experts, with many shuttles between the interlocutors. The format is direct questions with direct answers. Always try to divide your problem into smaller problems, and ask separately about each of them. So the content is more likely to be useful to people other than you. Keep turning the question while you’re fiddling with the code doesn’t work well here.

Show 3 more comments

3 answers

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>

4


Let me give you an example - explanation - superficial to pass the idea. Basically you have a DIV-PAI to include comments. When to submit the form via AJAX, just create the formatted element at the beginning using prepend using comment ID as reference for removal.


comment 3

comment 2

comment 1


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 to create the element with the delete button and the comment text. Using prepend the comment sent appears at the top of DIV-PAI.


Delete

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

delete will take the attribute class containing the comment ID and remove the element in case of Success.


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 becoming redundant. You can format the comment block in PHP and send as json. Home case is a case.

I removed the variables of js to make the code smaller, I believe that this step is no mystery.

  • @Kevinmtk, if you’re using PDO, just use lastInsertId to send the comment ID. You don’t know how to do an Insert in MYSQL?

  • I see no problem with that. About Insert-id.

  • @Kevinmt Bom, append rears at the end and prepend creates at the beginning. You choose where you want to insert the comment, I just gave the element reference. Any request via AJAX only needs PHP to give a simple echo - in case of string.

  • Yes, echo $last_ins_id will send the ID. The example I gave is a basis for you to adapt what you have already done - it is not complicated. Any question just comment, anyone can give a support here.

3

This is actually quite simple to do in ajax. I’ll give you an example on which to base:

http://blog.clares.com.br/utilizando-metodo-post-do-jquery-php/

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

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

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

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

If you have any more problems, let me know I’ll try to help you in another way.

  • 2

    If it doesn’t work out here, I’ll explain it better, but here’s the principle. Test the example as it is here and then adapt your need with mysql.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.