Show post with ajax

Asked

Viewed 819 times

4

I’m starting to log into jQuery only I need someone to write an opinion on my website and it will appear right below without having to update the page. wanted a person when inserting anything in the database that content appears right 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 the 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())"); 

4 answers

2


Okay, so dividing by parts:

To commit when you click "Enter" you can use:

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

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

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

$(".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 all that’s left prevent/stop form Ubmit. You can do this with:

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

but if you never want to submit to form then you don’t need a form and you can do it all with just imput...

Note: in your code you have <?php echo $_SESSION['user_id'] ?>. Missing there ; before ?>, as it is wrong.

Nota2: I used an object on data, jQuery also accepts a string, but I find it cleaner/clear/readable like this.

1

I built what you want quickly using HTML and jQuery. I didn’t mess with CSS. Otherwise, if you want these data to be saved in the database, you will need to mess with AJAX. In this case, within the click event, you will have to use AJAX to send a request to a PHP file (or other language) that will be in charge of connecting+inserting the message in 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>

<textarea class="mensagem"></textarea>
<button class="enviar">OK</button>

<ul id="mensagens">
  <!-- Irá adicionar mensagens pelo jQuery -->
</ul>

  • In the question title is referring to the use of ajax, your answer only shows how to create a temporary element on the page.

0

You can do as follows...by taking advantage of @Yosh’s 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:'page.php', will be a separate page, which will receive the text and do the entire insertion process in the database...

hope it helps!

  • Help was here trying to get it to work but it’s not working

0

You can do it like this

     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 saveComenter. 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 you use to fetch comments from the bank and will do a Reload in the div causing the new comment to appear.

Savecomentarios

 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;
}
  • I’m sorry but I didn’t quite understand how to implement this I’m now going deeper into ajax because I’m in need

Browser other questions tagged

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