How to save in MySql all data inserted in a form-control

4

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

Afterenteringandtypingenterthedatawouldalreadybesavedinthebd.

Whatisthebestwaytodothis?

Hereistheexcerptfrommyform:

<!--Domainstart--><labelfor="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 do not think I know how to "get" the data entered in this table or how to perform this insertion (in case I throw the data to the controller in some way (post maybe?)).

I tried some keyevent functions but no success (my fault).

Edit1 @

With alert you can 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 at times and come blank.

Doubt continues on how I will do to save the data in the bank as soon as the user enters an item. Inserted - saved.

    
asked by anonymous 08.05.2018 / 03:06

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 as follows:

  • Collect data from form : Look at this post on serializeArray()
  • Convert them to JSON format: Explained below
  • Sending them via AJAX to PHP
  • In PHP script convert them to array with json_decode() and save in BD
  • If you get PHP's successful response, insert the item on 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 view more in this post or jQuery documentation .

    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 have helped.

    EDITION

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

    $.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();
            }
        });
    

    STEP 4 , the correct one 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 is empty since content-type of request ( read more here ) will be application/json (passed by the ajax function) which is not supported by the variable $_PHP according to its documentation .

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

        
    08.05.2018 / 15:37