Show post with ajax

4

I'm starting to get into jQuery only as I need on my site that a person write an opinion and it appears right below without having to refresh the page. wanted a person to enter anything in the database given that this content appears on the page without having to update.

I need some lights on how to do this.

Code that I'm using

JS

$(function () {
    $(".submit_button").click(function () {
        var textcontent = $("#comentario").val();
        var dataString = 'id_estabelecimento=<?php echo $row->id; ?>&user_id=<?php echo $_SESSION['
        user_id '] ?>&opiniao=' + textcontent;
        if (textcontent == '') {
            alert("Por favor escreva um comentário..");
            $("#comentario").focus();
        } else {
            $("#flash").show();
            $("#flash").fadeIn(400).html('<span class="load">Aguarde por favor..</span>');
            $.ajax({
                type: "POST",
                url: "ajax/adicionar_comentario.php",
                data: dataString,
                cache: true,
                success: function (html) {
                    $("#show").after(html);
                    document.getElementById('comentario').value = '';
                    $("#flash").hide();
                    $("#comentario").focus();
                }
            });
        }
        return false;
    });
});

HTML

<form method="post" name="form" action="">
    <input type="hidden" name="valida" id="valida" value="ok" />
    <table border="0" bgcolor="#E9EAED" style="margin:0px 0px 30px 0px;" width="100%" cellpadding="0" cellspacing="0">
        <?php if($_SESSION[ 'FBID'] || $_SESSION[ 'user_id']){ ?>
        <tr>
            <td valign="top">
                <div id="flash" align="left"></div>
                <div id="show" align="left"></div>
            </td>
        </tr>
        <tr>
            <td valign="top" width="7%">
                <div style="padding:15px 5px 5px 20px;">
                    <img width="33" height="33" src="<?php echo $_SESSION['user_foto'] ?>" />
                </div>
            </td>
            <td valign="top" width="93%">
                <div style="padding:15px 20px 15px 5px;">
                    <input type="text" style="width:100%; height:33px;" placeholder="Escreve um comentário..." id="comentario" name="comentario" value="">
                </div>
                <input type="submit" id="submit" style="display:none;" class="submit_button">
            </td>
        </tr>

php code of file adiconar_comentario.php

session_start();
require_once("../gtm/bd/funcoes.php");
ligarBd();  

mysql_query("INSERT INTO comentarios (user_id, post_id, comentario, data) VALUES('".$_REQUEST['user_id']."', '".$_REQUEST['id_estabelecimento']."', '".$_REQUEST['opiniao']."', now())"); 
    
asked by anonymous 04.02.2015 / 17:05

4 answers

2

Ok, then dividing by parts:

To submit when the user clicks on "Enter" you can use:

$('#comentario').on('keydown', function(e){
    if (e.which != 13) return true;
    $('#submit').click();
});

In this way he clicks the hidden button only when e.wich == 13 (the key is "Enter").

To send this comment to the database you can optimize your code for:

$(".submit_button").click(function () {
    var input = document.getElementById('comentario');
    var textcontent = input.value;
    var data = {
        id_estabelecimento: "<?php echo $row -> id; ?>",
        user_id: "<?php echo $_SESSION['user_id']; ?>",
        opiniao: textcontent
    };

    $("#flash").html('<span class="load">Aguarde por favor..</span>').fadeIn(800);
    $.ajax({
        type: "POST",
        url: "ajax/adicionar_comentario.php",
        data: data,
        cache: true,
        success: function (html) {
            $("#show").after(html);
            input.value = '';
            $("#flash").hide();
            input.focus();
        }
    });
    return false;
});

Now just missing prevent / stop the form submit. You can do this with:

$('form').on('submit', function (e) {
    e.preventDefault();
});

But if you never want to submit to form then you do not need a form and you can do everything with the imput ...

Note : In your code you have <?php echo $_SESSION['user_id'] ?> . ; is missing before ?> , just as it is giving error.

Note2 : I used an object in data , jQuery also accepts a string, but I find it cleaner / clearer / readable as well.

    
06.02.2015 / 00:48
1

I put what you want quickly using HTML and jQuery. I did not move with CSS. Other than that, if you want this data to be saved in the database, you will need to tinker with AJAX. In this case, within the click event, you will have to use AJAX to send a request to a PHP (or other language) file that will be in charge of making the connection + insertion of the message into the database.

$(function() {
  
  $("button.enviar").click(function() {
    
    var mensagem = $("textarea.mensagem").val();
    
    limparCampo();
    
    if($.trim(mensagem)==""){
      return false;
    }
    
    $("#mensagens").prepend('<li>' + mensagem + '</li>');
    
  });
  
});

function limparCampo(){
  $("textarea.mensagem").val("");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaclass="mensagem"></textarea>
<button class="enviar">OK</button>

<ul id="mensagens">
  <!-- Irá adicionar mensagens pelo jQuery -->
</ul>
    
04.02.2015 / 17:17
0

You can do so

     function salvarComentario(){
        $.post("/caminho/para/funcao/save-comentario", {comentario: $('#campo_comentario').val()}, function(d) {
             if(d === "true" ){
                $("#id_div_comentarios").load('caminho/para/recuperar/comentarios',"#id_div_comentarios");      
            } else {
                alert("falha ao salver seu comentario");
            }

        });
    }

This function will send the value of the comment field to a function saveContents. If the return is true this part $("#id_div_comentarios").load('caminho/para/recuperar/comentarios',"#id_div_comentarios"); will make a request in the function that you use to search the bank's comments and will reload the div causing the new comment to appear.

SaveComments

 public function saveComentariosAction() {
    $request = $this->getRequest();
    if ($request->isPost()) {
        $aux = $request->getPost();
        $values = get_object_vars($aux);
        // codigo para salver o comentario no banco
        //verificar se foi salvo e dar um return true ou false;
    }
    return $boolean;
}
    
04.02.2015 / 17:31
0

You can do as follows ... taking advantage of the @YoSH code

$(function() {
   $("button.enviar").click(function() {
     var mensagem = $("textarea.mensagem").val();

     if($.trim(mensagem)==""){
       return false;
     }else{
       var dados = "mensagem="+mensagem;
       $.ajax({
          url: 'pagina.php',
          type: 'POST',
          data: dados,
          success:function(result){
             if(result){
                $("#mensagens").prepend('<li>' + mensagem + '</li>');
             else{
                alert("Não foi possível inserir seu comentário");
             }
          }
       })
     }    
   });
});

Where url: 'pagina.php' , it will be a separate page, which will receive the text and do the whole process of insertion into the database ...

I hope it helps!

    
04.02.2015 / 19:17