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

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

我的表单的源代码在这里: 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的情况下完成所有这些操作,并使用vanilla JS与本机LocalStorage API进行交互。

PHP:

 

Below is the data retrieved from SERVER

Server Timezone : ' . date_default_timezone_get() . ''; $current_date = date('d/m/Y == H:i:s '); print "

Server Time : " . $current_date . "

"; $dataObject = $_POST; //Fetching all posts echo "
"; //making the dump look nice in html. var_dump($dataObject); echo "

"; //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: