How to save all data inserted into a form-control in Mysql

Asked

Viewed 170 times

4

Guys, how can I make a script to save all data right after its insertion. In case the view would be this.

inserir a descrição da imagem aqui

After typing and typing enter the data would already be saved in the comic.

What’s the best way to do that?

Here’s the excerpt from my form:

<!-- Domain start -->
    <label for="domain_input">Domains</label>
    <div class="input-group">
        <input id="domain_input" name="domain_input" type="text" class="form-control" placeholder="Add domain" required="required" pattern="[A-Za-z0-9]{1,20}"/>
        <span class="input-group-btn">
            <button id="add_domain_button" class="btn btn-default" type="button">
                <i class="glyphicon glyphicon-plus"></i>
            </button>
        </span>
    </div>
    <br/>
    <table id="domain_list" class="table table-responsive">

    </table>

</div>
<!-- Domain end -->

I believe I don’t know how to "take" the data entered in this table and how to do this (in case throw the data to the controller somehow (post maybe?)).

I tried with some keyevent functions but without success (my fault I believe).

Edit1@

Can with Alert show some data entered in the table with the following code

<script>
  function testa() { 
    $('#lc_searchresult > table > tbody > tr').each(function() {
    var data = $(this).find('td').text();
    alert(data);        
}); }
</script>

However, it seems to fail sometimes and come field blank.

The doubt continues on how I will save the data in the database as soon as the user insert an item. Inserted - saved.

  • 1

    It is quite wide your question. Not that it is not good. A solution, quite used, would be to use AJAX. With javascript you "call" a php file that saves this data and updates a div. As if it were a "chat". Give a search, have many examples on the internet. If you have a more specific problem there you post it here it will be easier to help you.

  • I guess I couldn’t explain myself, I found some examples, but I’m really not good with js and I wanted to continue writing code that I can understand. Basically I want to perform a query and save in the database each time the user enters something in this field. I already found "n" examples, even at the moment I’m trying, <script> $("input[name=domain_input]"). keypress(Function(){ $.post( "<?=base_url()?>Protocol/add_domain", { given: $("input[name=domain_input]").val() } ); }); </script> but I still can’t get the table data right.

  • I get it. Put this code you mentioned here, in the question. It will help someone to answer you. I have saved here in the favorites.

  • 1

    If no one answers by tomorrow. I’ll make an example for you.

  • I appreciate the help, buddy, have a great night.

1 answer

3


The question does not include jQuery but using this framework sometimes makes the work easier, so one way you could do what you want is the following:

  1. Collect data from form : Look at this post about serializeArray()
  2. Convert them to JSON format: Explained below
  3. Send them via AJAX to PHP
  4. In the PHP script convert them to array with json_decode() and save in comic
  5. If you get a successful PHP response, insert the item in the page.

OBS:

STEP 1

The data collected from the form with serializeArray() will be in the following format

[ { name: "domain-input", value: "meuConteúdo" }, 
  { name: "domain-input2", value: "conteúdo qualquer" } 
] 

STEP 2

var unindexed_array = $("form").serializeArray();  // Coleta os dados do form
var jsonData = {}

$.each(unindexed_array, function(i, item) {
    // Para cada item em 'unindexed_array', fazer o que está aqui dentro.
    jsonData[item["name"]] = item["value"];  // salva 
});
    

After that, jsonData will be in the following format (JSON):

jsonData = { 
     "domain-input" : "meuConteúdo",
     "domain-input2" : "conteúdo qualquer"
 }

STEP 3

$.ajax({
        data: jsonData,           // dados a serem enviados
        dataType: "json",         // Formato do dado **recebido como resposta do servidor**.  html, json, text ...
        method: "post",           // post ou get
        url: "myPHPscript.php",   // url invocada
        success: function(data, textStatus, jqXHR) {
            // Executado em caso de sucesso.
            alert(data+" "+textStatus+" "+jqXHR+" ");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Executado em caso de erro.
            alert(jqXHR+" "+ textStatus+" "+ errorThrown);
            error();
        }
    });

You can see more in that post or in the documentation jQuery.

STEP 4

Receive data in PHP with json_decode().

PHP file:

$domain-input = json_decode($_POST["domain-input"], true);
$domain-input2 = json_decode($_POST["domain-input2"], true);
// Salva no BD

if (sucesso) { 
    $resposta_array['status'] = 'success';
} else {
    $resposta_array['status'] = 'error';
}

echo json_encode($resposta_array);

I hope I’ve helped.


EDITION

In the STEP 3, to ensure that the data passed is in JSON format, you can use the function JSON.stringify Javascript. What it does is convert the argument passed to it to a JSON string - which is expected by its name hehe. Still, add contentType: "application/json" the options object passed to the function $.ajax. So:

$.ajax({
        contentType: "application/json",  
        data: JSON.stringify(jsonData),                   // dados a serem enviados agora com a certeza de estarem em JSON.
        dataType: "json",                 // Formato do dado **recebido como resposta do servidor**.  html, json, text ...
        method: "post",                   // post ou get
        url: "myPHPscript.php",           // url invocada
        success: function(data, textStatus, jqXHR) {
            // Executado em caso de sucesso.
            alert(data+" "+textStatus+" "+jqXHR+" ");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Executado em caso de erro.
            alert(jqXHR+" "+ textStatus+" "+ errorThrown);
            error();
        }
    });

In the STEP 4, the correct would be

header('Content-Type: application/json; charset=utf-8');    // Altera o cabecalho para que o retorno seja em JSON

$aDados = json_decode(file_get_contents("php://input"), true); // Ver comentário abaixo.

// Verificar se foi recebido dados
// Usar assim: $aDados['domain-input']
// Salvar no BD

if (sucesso) { 
    $resposta_array['status'] = 'success';
} else {
    $resposta_array['status'] = 'error';
}

echo json_encode($resposta_array);         // Converte para JSON e imprime na página.

The expression file_get_contents("php://input") is used to collect data sent by AJAX because $_POST will be empty since the content-type of the request (read more here) will be application/json (passed by the ajax function) which is not supported by the variable $_PHP according to your documentation.

A problem caused by this (and which may not make a difference to most cases) is that php://input will not be available if the form be sent using enctype="multipart/form-data" which means it won’t be possible to include, for example, image uploads. For your case, there doesn’t seem to be any problems since you will only send texts.

  • 1

    Great answer.

  • 1

    Dude, your answer was just fantastic. There is a lot of material about this on the internet, but for those who are starting in the world of js gets all a bit confused. Again, thank you very much.

  • I am glad that the answer helped you. I made some important issues in order to work. Any questions ask here and I or anyone else can try to help you.

Browser other questions tagged

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