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

18,378

Solution 1

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>

NOTE: Replace the file format of your_data file to html in the PHP code if you want your JSON data in HTML format.

Solution 2

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)  ;  
Share:
18,378
Bhanu Chawla
Author by

Bhanu Chawla

Head of Digital in London working for Cornerstone OnDemand Inc. Part of the EMEA Marketing Team. Love Android (AOSP), Spotify addict, Proud Geek, Big Data enthusiast and all things Marketing.

Updated on July 19, 2022

Comments

  • Bhanu Chawla
    Bhanu Chawla almost 2 years

    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 problem is that I have multiple fields instead of a single field and I want to save the output (localStorage) in an HTML (or any other format) file instead of showing it in an #output div.

    How can I do that?

    You can see my work that I've done till now here: Save form data using AJAX to PHP

    And here's my HTML/JS code: http://jsbin.com/iSorEYu/1/edit & PHP code http://jsbin.com/OGIbEDuX/1/edit

  • Bhanu Chawla
    Bhanu Chawla over 10 years
    That's alright but I want to save the fields in a file on the same server instead of outputting it on a div. You'll note that the html form is sending the data to another server using eloqua script as well. So what I'm trying to achieve here is send the data to eloqua using their script and save the data for my purpose as well. Possible?
  • DrColossos
    DrColossos over 10 years
    I updated to code, not sure what you exactly want to archive but simply saving data to a file can be done with file_put_contents
  • Bhanu Chawla
    Bhanu Chawla over 10 years
    Right. So I've updated my code but it isn't doing anything. See the latest code here: jsbin.com/iSorEYu/4/edit & PHP: jsbin.com/OGIbEDuX/2/edit The other thing is that the form stopped posting data to the other server after I used your code. Checkout the live version here: hackingarticles.com/marketer
  • DrColossos
    DrColossos over 10 years
    Please pay attention to your code. You have a } too much. The server repsonds with an error 500 - Internal Server Error, meaning that there is an error in you code. Probably the mentioned one.
  • Bhanu Chawla
    Bhanu Chawla over 10 years
    Any luck with my updated code? Really appreciate your help here.