小编典典

使用AJAX将表单数据保存到PHP

ajax

如何将表单数据保存在文件或本地db(也许使用AJAX)中,该文件或数据通过表单操作将数据发送到外部db?

我的表单的源代码在这里:http :
//jsbin.com/ojUjEKa/1/edit

我应该对代码进行哪些更改(如果有)?

EDIT:
对。因此,我能够使用AJAX将数据存储到localStorage中,并希望将存储的数据发送到名为backend.php的文件中。这是我的html文件:http
//jsbin.com/iSorEYu/1/edit

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

AJAX在将字段存储在localStorage中的工作绝对正常,但是当尝试将数据发送到backend.php时出现了问题。我收到以下错误:

 [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

这是什么问题?


阅读 194

收藏
2020-07-26

共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>
2020-07-26