jQuery で AJAX リクエストを行う方法を尋ねている場合、これが 1 つの方法です。
HTML:
<div id="message" style="display:none"></div>
<form action="script.php" method="post" id="myForm">
<select name="employees">
<option value="1">Joh Smith</option>
<option value="2">Janeh Doe</option>
</select>
</form>
JQuery:
$('#myForm').on('submit', function() {
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: $this.attr('method'),
data: $this.serialize(),
dataType: 'json',
success: function(response) {
if(response.success) {
$('#message')
.text('Database updated successfully')
.addClass('success')
.show();
}
else {
$('#message')
.text('Error happened, AJAX request completed but PHP had a problem.')
.addClass('error')
.show();
}
},
error: function() {
alert('Error happened, AJAX request could not be completed.');
}
});
return false;
});
PHP でデータベースが正常に更新された場合:
echo json_encode(array(
'success' => true
));
それ以外は:
echo json_encode(array(
'success' => false
));