繁体   English   中英

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

[英]Save form data using AJAX to PHP

如何将表单数据保存在文件或本地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

这里有什么问题?

LocalStorage将是您最好的选择。 我建议使用storejs,因为它们的API非常简单,易于使用并且是x浏览器。

然后,您可以触发将表单值存储在每个字段的“模糊”事件中。

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

当您准备提交到服务器时,可以使用以下内容:

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

您当然可以在没有storejs的情况下完成所有这些操作,并使用香草JS与本地LocalStorage API进行交互。

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM