フォームからデータベースにデータを送信しようとしています。 使用しているフォームは次のとおりです。
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
典型的なアプローチはフォームを送信することですが、これではブラウザがリダイレクトされてしまいます。jQueryとアヤックスフォームのすべてのデータをキャプチャして PHP スクリプト (例: form.php ) に送信することは可能ですか?
ベストアンサー1
基本的な使い方.ajax
次のようになります:
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
jQuery:
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
注: jQuery 1.8 以降、.success()
、.error()
は非推奨となり、.complete()
代わりに 、 、 が使用されるようになりました。.done()
.fail()
.always()
注: 上記のスニペットはDOMの準備ができた後に実行する必要があることに注意してください。そのため、$(document).ready()
ハンドラー (または$()
省略形を使用)。
ヒント:鎖コールバック ハンドラは次のようになります。$.ajax().done().fail().always();
PHP (つまり、form.php):
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;
注: 常に投稿されたデータをサニタイズするインジェクションやその他の悪意のあるコードを防ぐためです。
省略形を使うこともできます.post
.ajax
上記の JavaScript コードの代わりに:
$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
注: 上記の JavaScript コードは jQuery 1.8 以降で動作するように設計されていますが、jQuery 1.5 までの以前のバージョンでも動作するはずです。