使用AJAX到PHP保存表单数据

问题描述:

我如何保存表单中的数据文件或本地数据库(可能使用AJAX),它通过表单操作将数据发送到外部数据库?

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?

该人士$ ​​C $ C我的表是在这里: http://jsbin.com/ojUjEKa/ 1 /编辑

The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit

什么变化(如果有的话)我应该做的code?

What changes (if any) should I make to the code?

EDIT:

右键。所以我能够将数据存储到localStorage的使用AJAX和要发送跨存储到一个名为backend.php文件中的数据。这是我的html文件: http://jsbin.com/iSorEYu/1/edit

这是我的backend.php文件: http://jsbin.com/OGIbEDuX/1/edit

and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit

阿贾克斯正在精绝存储在localStorage的领域,但出问题时,它尝试将数据通过发送到backend.php。我收到以下错误:

The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:

 [24-Jan-2014 08:40:34 America/Chicago] PHP Notice:  Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
 [24-Jan-2014 08:40:34 America/Chicago] PHP Warning:  Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
 [24-Jan-2014 08:40:58 America/Chicago] PHP Notice:  Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
 [24-Jan-2014 08:40:58 America/Chicago] PHP Warning:  Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10

有什么问题吗?

What's the issue here?

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);
?>

记者:

<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>