我尝试使用jQuery(AJAX)向我的MySQL数据库提交表单。当我按下提交按钮时,我收到用JavaScript编写的失败消息“失败”。我认为我的JavaScript语法有问题。
HTML / JavaScript
<form method="post" action="opslaan.php">
<input type="text" id="itmnlid" name="tmnlid">
<input type="text" id="ibesproken" name="besproken">
<input type="text" id="iafspraken" name="afspraken">
<button type="submit">Save</button>
<p id="result"></p>
</form>
<script>
$("form").submit(function(e) {
e.preventDefault();
$.post(
'opslaan.php', {
id: $("#itmnlid").val(),
besproken: $("#ibesproken").val(),
afspraken: $("#iafspraken").val()
},
function(result) {
if (result == "succes") {
$("#result").html("succes");
} else {
$("#result").html("failed");
}
}
);
});
</script>
PHP:
$id = $_POST["id"] ;
$besproken = $_POST["besproken"];
$afspraken = $_POST["afspraken"];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO coaching (id, besproken, afspraken)
VALUES ('$id', '$besproken', '$afspraken')";
if ($conn->query($sql) === TRUE) {
echo "succes";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
答案 0 :(得分:1)
$("form").submit(...)
事件未触发。您必须用$(document).ready(...)
包围它。喜欢:
$(document).ready(function () {
$("form").submit(function (e) {
//...
});
});
否则,它似乎可以工作。
表结构:
CREATE TABLE `coaching` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tmnlid` varchar(8) DEFAULT NULL,
`besproken` varchar(1000) DEFAULT NULL,
`afspraken` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
index.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function (event) {
$.ajax({
method: 'post',
dataType: 'html',
url: 'opslaan.php',
data: {
'tmnlid': $('#tmnlid').val(),
'besproken': $('#besproken').val(),
'afspraken': $('#afspraken').val(),
},
success: function (response, textStatus, jqXHR) {
if (response == true) {
$('#result').html('Record successfully saved.');
} else {
$('#result').html(jqXHR.responseText);
}
},
error: function (jqXHR, textStatus, errorThrown) {
/*
* If the status code of the response is a custom one (420 for example),
* defined by you in php, then the corresponding error message is displayed.
* Otherwise, the displayed message will be a general user-friendly
* one - so that no system-related infos will be shown.
*/
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
$('#result').html(message);
},
complete: function (jqXHR, textStatus) {
//...
}
});
});
});
</script>
</head>
<body>
<h3>Demo</h3>
<p id="result"></p>
<form method="post" action="opslaan.php">
<label for="tmnlid">Tmnlid:</label>
<!-- @todo-1 -->
<input type="text" id="tmnlid" name="tmnlid" maxlength="8"> (max. 8 chars)
<br/>
<label for="besproken">Besproken:</label>
<input type="text" id="besproken" name="besproken">
<br/>
<label for="afspraken">Afspraken:</label>
<input type="text" id="afspraken" name="afspraken">
<br/>
<button type="button" id="submit" name="submit" value="save">
Save
</button>
</form>
</body>
</html>
opslaan.php:
<?php
require 'handlers.php';
require 'connection.php';
/*
* =======================
* Read the posted values.
* =======================
*/
//@todo-1
$tmnlid = isset($_POST['tmnlid']) ? $_POST['tmnlid'] : '';
$besproken = isset($_POST['besproken']) ? $_POST['besproken'] : '';
$afspraken = isset($_POST['afspraken']) ? $_POST['afspraken'] : '';
/*
* ===========================
* Validate the posted values.
* ===========================
*/
//@todo-1
if (empty($tmnlid)) {
/*
* This custom response header triggers the ajax error, because the status
* code begins with 4xx (which corresponds to the client errors). Here is
* defined "420" as the custom status code. One can choose whatever code
* between 401-499 which is not officially assigned, e.g. which is marked
* as "Unassigned" in the official HTTP Status Code Registry. See the link.
*
* @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
//@todo-1
header('HTTP/1.1 420 Please provide the tmnlid.');
exit();
}
//@todo-1
elseif (strlen($tmnlid) > 8) {
header('HTTP/1.1 420 The tmnlid must contain only 8 characters.');
exit();
}/* Other validations here using elseif statements */
//==================================================
// Here the validations for the other posted values.
// ...
//==================================================
/*
* ================
* Save the record.
* ================
*/
//@todo-1
$sql = 'INSERT INTO coaching (
tmnlid,
besproken,
afspraken
) VALUES (
?, ?, ?
)';
/*
* Prepare the SQL statement for execution - ONLY ONCE.
*
* @link http://php.net/manual/en/mysqli.prepare.php
*/
$statement = $connection->prepare($sql);
/*
* Bind variables for the parameter markers (?) in the
* SQL statement that was passed to prepare(). The first
* argument of bind_param() is a string that contains one
* or more characters which specify the types for the
* corresponding bind variables.
*
* @link http://php.net/manual/en/mysqli-stmt.bind-param.php
*/
//@todo-1
$statement->bind_param('sss', $tmnlid, $besproken, $afspraken);
/*
* Execute the prepared SQL statement.
* When executed any parameter markers which exist will
* automatically be replaced with the appropriate data.
*
* @link http://php.net/manual/en/mysqli-stmt.execute.php
*/
$statement->execute();
echo TRUE;
handlers.php:
<?php
/*
* Include this page in all PHP pages of the application.
*
* This page contains:
* - The APP_ENV constant, used to decide in which environment this application runs.
* - The functions for handling all the errors, or exceptions, raised by the application.
* - The code for setting them as error/exception handlers.
* - The code deciding if the errors should be displayed on the screen. The errors
* display MUST be activated ONLY in the development stage of the application. When
* the website goes live, ALL ERRORS must be written in a/the log file and NO ERRORS
* should be displayed on screen, but only a general, user-friendly message, or a
* custom error page.
*/
/*
* Decide in which environment this application runs. Possible values:
* - 'prod' (app in production, e.g. live). The errors are not displayed, but only logged.
* - 'dev' (app in development). The errors are displayed on screen and logged.
* - 'test' (app in tests). Same as 'dev'.
* - etc.
*/
define('APP_ENV', 'dev');
// Activate the errors/exceptions logging.
ini_set('log_errors', 1);
// Set the error reporting level: report all errors.
error_reporting(E_ALL);
// Decide how to handle the errors/exceptions.
if (APP_ENV === 'prod') { // App in production, e.g. live.
/*
* DON'T display the errors/exceptions on the screen. Just let the error and
* exception handler print a user-friendly message, or show a custom error page.
*/
ini_set('display_errors', 0);
// Set the handler functions.
set_error_handler('errorHandler');
set_exception_handler('exceptionHandler');
} else { // App in development, tests, etc.
// Display the errors/exceptions on the screen.
ini_set('display_errors', 1);
}
/**
* Error handler:
* - Print a user-friendly message, or show a custom error page.
* - Log the error.
*
* @link http://php.net/manual/en/function.set-error-handler.php set_error_handler.
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
*/
function errorHandler($errno, $errstr, $errfile, $errline) {
echo 'An error occurred during your requestsss. Please try again, or contact us.';
error_log('Error ' . $errno . ' - ' . $errstr . ' in file ' . $errfile . ' on line ' . $errline);
exit();
}
/**
* Exception handler:
* - Print a user-friendly message, or show a custom error page.
* - Log the error.
*
* @link http://php.net/manual/en/function.set-exception-handler.php set_exception_handler.
* @param Exception $exception
*/
function exceptionHandler($exception) {
echo 'An error occurred during your request. Please try again, or contact us.';
error_log('Exception ' . $exception->getCode() . ' - ' . $exception->getMessage() . ' in file ' . $exception->getFile() . ' on line ' . $exception->getLine());
exit();
}
connection.php:
<?php
/*
* This page contains the code for creating a mysqli connection instance.
*/
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');
/*
* Enable internal report functions. This enables the exception handling,
* e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
* (mysqli_sql_exception).
*
* MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
* MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
*
* @link http://php.net/manual/en/class.mysqli-driver.php
* @link http://php.net/manual/en/mysqli-driver.report-mode.php
* @link http://php.net/manual/en/mysqli.constants.php
*/
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create a new db connection.
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
答案 1 :(得分:0)
我认为您的检查方式有误。因为成功插入php文件后将返回“成功创建新记录”。因此,您必须检查结果。用于检查ajax的js代码应该像
if (result == "New record created successfully"){
$("#result").html("succes");
}else{
$("#result").html("failed");
}
答案 2 :(得分:-1)
我认为您需要将echo
与json_encode
一起使用。
json_encode文档:http://php.net/manual/pt_BR/function.json-encode.php
并在JS上的POST中。像这样使用json
:
$.post('endpoint.php', YOUR_DATA_OBJECT, function (result) {
//something
}, 'json');