How to save data from a form automatically?

Asked

Viewed 1,828 times

1

Hello, good night, I need a help from you, I want to automatically save what is typed in a text area in my mysql database, I’ve heard that has how to do with Ajax, I tried with this code I have there, but it’s not working, the data is not being saved.

    <script>
            setInterval(function() {
    $.ajax({
        url: 'http://www.dpaulatreinamentos.com/system/teste03/views/pages/pegaIdLousa_edit.php?id_aula=<?php echo $id_aula; ?>',
        type: 'post',
        data: {
            'Lousa': $('#editor5').val()
        },
        success: function() {
        } 
    });

}, 5000 /* 1000 = 1 segundo, aí o tempo você quem determina */);
        </script>

Part of Form

<form method="post" action="http://www.dpaulatreinamentos.com/system/teste03/controllers/edit_lousas.php?id_aula=<?php echo $id_aula; ?>">
                <textarea name="Lousa" id="editor5" rows="20" cols="10">
            <?php echo $select_lousa; ?>
        </textarea>
        <script>
            // Replace the <textarea id="editor1"> with a CKEditor
            // instance, using default configuration.
            CKEDITOR.replace( 'editor5' );
        </script>

  <input type="submit" value=" Salvar " class="btn-save-medium" />
</form>
  • Not saving or not sending the data to the server? If the data goes but does not save, put the code that makes the insertion in the database.

  • If I click the button the data saves normally, plus if I just enter the data does not send, only stay on the screen even more in the database nothing happens

  • someone knows how to?

  • It would be more feasible to store this data when typing in the browser’s localStorage. Only with the click would they be inserted into the database.

  • That no longer solves my problem, is a digital whiteboard system, where I will have the first instance with the teacher typing and in real time being sent to the server and at the same time the student accessing the viewing part of this whiteboard, what really can’t is having the click understand

  • I already ran the tests on my server and I will have a delay of 3 seconds until everything happens, I think enough for the class to happen, more needed this part first

Show 1 more comment

2 answers

1


Run the following code

$(function(){
  editor5 = CKEDITOR.replace( 'editor5' );
  setInterval(function(){ 
    $.ajax({
      type: "post",
      url: "link",
      data: {
        valor: CKEDITOR.instances.editor5.getData()
      }
    })
  }, 3000);
  editor5 = CKEDITOR.replace( 'editor5' );
})

0

William I don’t fully understand what you want, but I’ll try to help you with what I know, in case it’s not quite right let me know that I edit.

I use to $.get in jQuery itself

$.get("local.php", //executa o arquivo no local especificado
   {"nome_variavel1":variavel1, "nome_variavel2":variavel2}, //variaveis a serem postadas
   function(data){ //função de retorno
      alert(data); //alerta com o retorno
});

Taking this into account and remembering that it is not mandatory to use the form, you can make asynchronous requests (without synchronism) in php and successively in the database.

Example:

<textarea id="texto" ></textarea>
<button id="enviar"></button>
<p id="resultado"></p>

<script>
 var texto = $("#texto").val();
 if(texto != ""){ // se o textarea não estiver em branco
   $.get("local.php", // informe o arquivo aqui
      {"texto":texto}, //postando o texto para o arquivo
      function(data){ //solicitando a resposta do arquivo
        $("#resultado").html(data); //imprimindo a resposta no html
   });
 }else{ //caso o usuario o usuário não coloque nada
   $("#resultado").html("Escreva algo!!!");
 }
</script>

PHP(local.php)

include "conexao.php"; //inclua seu arquivo de conexão com o banco ou descreva sua conexão, suponhamos que o método de conexão se chama $conn

$texto = $_POST['texto'];
$sql = "INSERT INTO (texto) VALUES ('$texto')"; //aqui vai ser o insert no banco
if($conn->query($sql)==TRUE){ //realizando a execução da query utilizando o método de conexão com o banco $conn, se tudo correr bem imprimi "Sucesso"
  echo "Sucesso"; //isto retornara para $("#resultado") se tudo der certo
}else{ //se não gera uma mensagem de erro
  echo "Houve um erro na inserção de dados no banco!"; //isto retornara para $("#resultado") se tudo der errado
}

Actually it’s very simple, as you train you will see this, you just have to take care not to get lost!

  • So my system is for live distance learning by video conferencing, there’s a part of my system called Whiteboard, where it will serve as a framework for the students and the teacher, by the time it is written on the board I want you to send it to php and send it directly to the database without having to click anything to make it happen, that is, it has to happen automatically one in a second or when typing in the field

  • The student part already solved, I put an echo with the server data and an automatic refresh on the page, is already working, only the part of the teacher even if I’m not getting, that has to send the text automatically.

  • Sorry for the delay, I hope there have solved this. You can use the $('input'). keyup(Function(){ receive the data here and send it to php the same way }); so whenever the user type it will run the code, the bad thing is that the code keeps firing several times to the database.

Browser other questions tagged

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