Javascript 使用AJAX向MySQL提交表单

Javascript 使用AJAX向MySQL提交表单,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我尝试使用jQuery(AJAX)向MySQL数据库提交表单。当我按下submit按钮时,我得到了我用JavaScript编写的失败消息“failed”。我认为我的JavaScript语法有问题 HTML/JavaScript <form method="post" action="opslaan.php"> <input type="text" id="itmnlid" name="tmnlid"> <input type="text" id="ibesp

我尝试使用jQuery(AJAX)向MySQL数据库提交表单。当我按下submit按钮时,我得到了我用JavaScript编写的失败消息“failed”。我认为我的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>

拯救

$(“表格”)。提交(功能(e){ e、 预防默认值(); 美元邮政( “opslan.php”{ id:$(“#itmnlid”).val(), 最好:$(“#ibesproken”).val(), afspraken:$(“#iafspraken”).val() }, 功能(结果){ 如果(结果=“成功”){ $(“#结果”).html(“成功”); }否则{ $(“#结果”).html(“失败”); } } ); });
PHP:

$id=$\u POST[“id”];
$besproken=$_POST[“besproken”];
$afspraken=$_POST[“afspraken”];
$conn=newmysqli($servername、$username、$password、$dbname);
//检查连接
如果($conn->connect\u错误){
die(“连接失败:”.$conn->connect\U错误);
} 
$sql=“插入辅导(id、besproken、afspraken)
值(“$id”、“$besproken”、“$afspraken”)”;
if($conn->query($sql)==TRUE){
呼应“成功”;
}否则{
echo“Error:”.$sql.“
”$conn->Error; } $conn->close(); ?>
我认为您需要将
echo
json\u encode
一起使用

json_编码文档:

在你关于JS的帖子中。使用此
json
,如下所示:

$.post('endpoint.php',您的数据对象,函数(结果){
//某物

}“json”)

我认为您需要将
echo
json\u encode
一起使用

json_编码文档:

在你关于JS的帖子中。使用此
json
,如下所示:

$.post('endpoint.php',您的数据对象,函数(结果){
//某物

}“json”)

我想你查错了。因为php文件插入成功后将返回“New record created successfully”。所以你必须检查这个和结果。用于ajax结果检查的js代码应该如下

if (result == "New record created successfully"){
    $("#result").html("succes");
}else{
    $("#result").html("failed");
}

我想你查错了。因为php文件插入成功后将返回“New record created successfully”。所以你必须检查这个和结果。用于ajax结果检查的js代码应该如下

if (result == "New record created successfully"){
    $("#result").html("succes");
}else{
    $("#result").html("failed");
}
未触发
$(“表单”).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;
<!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>
<?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;
<?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();
}
<?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);
index.php:

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;
<!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>
<?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;
<?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();
}
<?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);

演示
$(文档).ready(函数(){
$(“#提交”)。单击(函数(事件){
$.ajax({
方法:“post”,
数据类型:“html”,
url:'opslan.php',
数据:{
“tmnlid”:$(“#tmnlid”).val(),
“besproken”:$(“#besproken”).val(),
'afspraken':$('afspraken').val(),
},
成功:函数(响应、文本状态、jqXHR){
如果(响应==true){
$('#result').html('记录已成功保存');
}否则{
$('#result').html(jqXHR.responseText);
}
},
错误:函数(jqXHR、textStatus、errorshown){
/*
*如果响应的状态代码是自定义代码(例如420),
*由您在php中定义,然后显示相应的错误消息。
*否则,显示的消息将是一个通用的用户友好型消息
*一个-这样就不会显示与系统相关的信息。
*/
var消息=(jqXHR.status===420)
?jqXHR.statusText
:“请求过程中出错。请重试。”;
$('#result').html(消息);
},
完成:函数(jqXHR,textStatus){
//...
}
});
});
});
演示

Tmnlid: (最多8个字符)
贝斯普鲁肯:
阿夫斯普拉肯:
拯救
opslan.php:

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;
<!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>
<?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;
<?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();
}
<?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);
未触发
$(“表单”).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;
<!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>
<?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;
<?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();
}
<?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);
index.php:

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;
<!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>
<?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;
<?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();
}
<?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);

演示
$(文档).ready(函数(){
$(“#提交”)。单击(函数(事件){
$.ajax({
方法:“post”,
数据类型:“html”,
url:'opslan.php',
数据:{
“tmnlid”:$(“#tmnlid”).val(),
“besproken”:$(“#besproken”).val(),
'afspraken':$('afspraken').val(),
},
成功:函数(响应、文本状态、jqXHR){
如果(响应==true){
$('#result').html('记录已成功保存');
}否则{