Send data from localStorage via AJAX to PHP and save it in an HTML file

前端 未结 2 620
借酒劲吻你
借酒劲吻你 2020-12-20 15:43

I want to send fields data from a form to a file via AJAX and I found this solution online: http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/

The only p

2条回答
  •  再見小時候
    2020-12-20 16:06

    You are overcomplocating things. The check for localStorage can be way simpler (other options). jQuery has a serialze() function that takes all form elements and serializes it. You can store them under "eloqua-fields" so you can find it again. No need to do some fancy random retrival.

    I'd like to add that not all of you code makes sense. Why use localstorage if you clear it every time the DOM is ready? Your validation does not abort the sending process if there are errors but I assume you just want to play around with stuff.

    $(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").val(""); //this ONLY clears input fields, you also need to reset other fields like select boxes,...
                alert("Now Passing stored data to Server through AJAX jQuery");
                $.ajax({
                   type: "POST",
                   url: "backend.php",
                   data: {data: fields},
                   success: function(data) {
                      $('#output').html(data);
                   }
                });
            } else {
                alert("Storage Failed. Try refreshing");
            }
        });
    });
    

    For the server part if you just want to store your data somewhere.

    $dataObject = $_POST['data'];
    $json = json_decode($dataObject);
    file_put_contents('your_data.txt', $json)  ;  
    

提交回复
热议问题