チュートリアルに従ってコードを適応させました。ここでは、「ID」値が提供されたときに、フォーム フィールドに AJAX を自動入力しようとしています。私は Jquery を初めて使用するので、このコードを使用できません。
編集 1: コードのテスト中、Jquery はフォームの送信と AJAX 要求の送信を妨げていません。
HTMLフォーム
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
Jquery コードを変更しようとしましたが、それでも動作しませんでした。ここでJqueryが問題を引き起こしていると思います。しかし、エラーまたはバグのあるコードを見つけることができません。あなたが私を正しい方向に向ければ、それは非常に役に立ちます。
編集2:使ってみた
return false;
それ以外の
event.preventDefault();
フォームが送信されないようにしますが、それでも機能しません。私がここで間違っていることは何か分かりますか?
Jクエリ
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}