Save form data using AJAX to PHP

前端 未结 2 1002
忘掉有多难
忘掉有多难 2021-01-24 14:08

How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?

The source code for my form is here: http:

相关标签:
2条回答
  • 2021-01-24 14:32

    LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.

    You could then trigger the form values to be stored on the "blur" event of each field.

    $('input').on('blur', function (e) {
      var el = e.target;
      store.set(el.attr('name'), el.val());
    });
    

    When you are ready to submit to the server, you could use something like the following:

    $('#formID').on('submit', function (e) {
      e.preventDefault();
      $.post('/my/save/route', store.getAll(), function () { ... });
    });
    

    You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.

    0 讨论(0)
  • 2021-01-24 14:46

    PHP:

    <h1>Below is the data retrieved from SERVER</h1>
    <?php
        date_default_timezone_set('America/Chicago'); // CDT
        echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
        $current_date = date('d/m/Y == H:i:s ');
        print "<h2>Server Time : " . $current_date . "</h2>";
    
        $dataObject = $_POST; //Fetching all posts
    
        echo "<pre>"; //making the dump look nice in html.
        var_dump($dataObject);
        echo "</pre>";
    
            //Writes it as json to the file, you can transform it any way you want
        $json = json_encode($dataObject);
        file_put_contents('your_data.txt', $json);
    ?>
    

    JS:

    <script type="text/javascript">
    $(document).ready(function(){
    localStorage.clear();
    
    $("form").on("submit", function() {
        if(window.localStorage!==undefined) {
            var fields = $(this).serialize();
    
            localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
            alert("Stored Succesfully");
            $(this).find("input[type=text]").val("");
            alert("Now Passing stored data to Server through AJAX jQuery");
            $.ajax({
               type: "POST",
               url: "backend.php",         
               data: fields,
               success: function(data) {
                  $('#output').html(data);
               }
            });
        } else {
            alert("Storage Failed. Try refreshing");
        }
    });
    });
    </script>
    
    0 讨论(0)
提交回复
热议问题