AJAX表单通信,显示生成的消息-如何


AJAX form communication, displaying resulting messages - how to?

我是ajax场景的新手,慢慢地掌握了它的窍门。我已经构建了一个相当实用的表单,除了一些我正在解决的细节。其中之一就是这个问题的原因。

我有一个表单,它通过ajax通过html->ajax->php->mysql的过程成功地更新到mysql数据库。然而,目前绝对没有通信消息或指示符从php返回到html,以指示成功或错误。作为使用ajax的新手,我们非常感谢您的帮助。

使用中的技术:jQuery、JavaScript、html、php

HTML表单(它的一部分,而不是完整的表单,因为这是不必要的):

<form id="<?=$applicationKey?>" name="<?=$applicationKey?>" action="./post.<?=$appNo.'.'.$applicationKey?>.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="token" value="<?=$sessionToken?>">
<input type="hidden" name="uID" value="<?=$uID?>">
<input type="hidden" name="uaID" value="<?=$uaID?>">
<input type="hidden" name="appID" value="<?=$appID?>">
 <table style="width: 100%; height: auto;">
  <tbody><tr>
   <td class="tright" style="width: 265px;">Name of the Applicant's Organisation:</td>
   <td><input type="text" id="input_1_1" name="input_1_1" placeholder="Name of the Applicant's Organisation" maxlength="64" value="<?=$input_1_1?>" required><span id="resultImg_1_1"></span><br>
   <div id="errorText_1_1" class="errorOutput"></div></td>
  </tr>
  <tr>
   <td class="tright">Contact Person:</td>
   <td><input type="text" id="input_1_2" name="input_1_2" placeholder="Contact Person" maxlength="64" value="<?=$input_1_2?>" required><span id="resultImg_1_2"></span><br>
   <div id="errorText_1_2" class="errorOutput"></div></td>
  </tr>
  <tr>
   <td class="tright">Telephone (Landline):</td>
   <td><input type="text" id="input_1_3" name="input_1_3" placeholder="Telephone (Landline)" maxlength="22" value="<?=$input_1_3?>" required><span id="resultImg_1_3"></span><br>
   <div id="errorText_1_3" class="errorOutput"></div></td>
  </tr>
  <tr>
   <td class="tright">Telephone (Mobile):</td>
   <td><input type="text" id="input_1_4" name="input_1_4" placeholder="Telephone (Mobile)" maxlength="22" value="<?=$input_1_4?>" required><span id="resultImg_1_4"></span><br>
   <div id="errorText_1_4" class="errorOutput"></div></td>
  </tr>
  <tr>
   <td class="tright">Email:</td>
   <td><input type="text" id="input_1_5" name="input_1_5" placeholder="Email" maxlength="64" value="<?=$input_1_5?>" required><span id="resultImg_1_5"></span><br>
   <div id="errorText_1_5" class="errorOutput"></div></td>
  </tr>
  <tr>
   <td class="tright">Fax:</td>
   <td><input type="text" id="input_1_6" name="input_1_6" placeholder="Fax" maxlength="22" value="<?=$input_1_6?>" required><span id="resultImg_1_6"></span><br>
   <div id="errorText_1_6" class="errorOutput"></div></td>
  </tr>
  <tr>
   <td class="tright">Address:</td>
   <td><textarea id="input_1_7" name="input_1_7" placeholder="Address" maxlength="120" required><?=$input_1_7?></textarea><span id="resultImg_1_7"></span><br>
   <div id="errorText_1_7" class="errorOutput"></div></td>
  </tr></tbody>
 </table>

包含的js文件如下(对于表单的这一部分):

function doSend_1_1() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_1', $('#input_1_1').serialize());
}
function doSend_1_2() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_2', $('#input_1_2').serialize());
}
function doSend_1_3() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_3', $('#input_1_3').serialize());
}
function doSend_1_4() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_4', $('#input_1_4').serialize());
}
function doSend_1_5() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_5', $('#input_1_5').serialize());
}
function doSend_1_6() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_6', $('#input_1_6').serialize());
}
function doSend_1_7() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_7', $('#input_1_7').serialize());
}
$("document").ready(function() {
    $("#input_1_1").blur(doSend_1_1);
    $("#input_1_2").blur(doSend_1_2);
    $("#input_1_3").blur(doSend_1_3);
    $("#input_1_4").blur(doSend_1_4);
    $("#input_1_5").blur(doSend_1_5);
    $("#input_1_6").blur(doSend_1_6);
    $("#input_1_7").blur(doSend_1_7);
})

最后,接收php部分处理这里显示的表单部分,看起来像这样:

<?php
// include the funcky stuff
include './conf/Funcs.php';
include './conf/DBconfig.php';
// GET the constants
$token = $_GET['token'];
$appID = $_GET['appID'];
$ident = $_GET['ident'];
// =================== TAB 1 ===================
// organisation
if(($ident) == "input_1_1") {
    $userInput = $_POST['input_1_1'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `organisation` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
// contactPerson
if(($ident) == "input_1_2") {
    $userInput = $_POST['input_1_2'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `contactPerson` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
// phoneLandline
if(($ident) == "input_1_3") {
    $userInput = $_POST['input_1_3'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `phoneLandline` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_INT, 22);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
// phoneMobile
if(($ident) == "input_1_4") {
    $userInput = $_POST['input_1_4'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `phoneMobile` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_INT, 22);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
// email
if(($ident) == "input_1_5") {
    $userInput = $_POST['input_1_5'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `email` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
// fax
if(($ident) == "input_1_6") {
    $userInput = $_POST['input_1_6'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `fax` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_INT, 22);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
// address
if(($ident) == "input_1_7") {
    $userInput = $_POST['input_1_7'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `address` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 128);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        $stmt->execute();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}

等等,以及我在这里没有引用的表格的其余部分。我意识到这里面有一些GET操作,这没关系。出于安全原因,我希望一些事情由GET完成,而不是由POST完成(我在这个例子中没有说明这一点,这与此无关)。正如我之前提到的,这是我的第一个ajax工作,所以我知道它不会是原始的。我现在对此很满意,不想展示几种不同的重写方式。我只需要知道如何发送一条来自php的消息,告诉html是否发生了成功的失败,如果失败,为什么。我在html中准备了相应的错误输出div,我还准备了一个span,用于对应一个漂亮的图像(勾选或弹出箭头,以引起人们对需要修复的问题的注意)。演示如何使用JSON(?)验证并发送回消息会很有帮助。我读过很多关于JSON的文章,尽管我还没有完全理解它。

在实践中,它并不像看上去那么复杂。当您在php中处理ajax请求时,在php中输出的任何内容都将被返回,您可以在javascript中使用它。

因此,如果您的php脚本中有echo 'hello';,hello将被发送回您的javascript。你几乎可以输出任何东西。

JSON是一种方便的输出格式,因为它在两种语言中都很容易处理。如果您的php中有一个关联数组,其中包含要发回的数据,您可以简单地执行以下操作:

$return = json_encode($my_data);
header('Content-Type: application/json');
echo $return;

然后,您可以在javascript:中获取这些数据

$.post( 'handler.php', function( data ) {
  // data now has the data structure from your php in it, ready to use.
});

这里有一个从php发回一些数据的例子(我相信你在实践中会做一些不同的事情,但只是围绕现有代码的一个例子):

$error_message = '';
if(($ident) == "input_1_1") {
    $userInput = $_POST['input_1_1'];
    if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
    try {
        $stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `organisation` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
        $stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 64);
        $stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
        $stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
        if( $stmt->execute() ) {
            $error_message = 'Success';
        } else {
            $error_message = 'Error';
        }
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
$return_data = array( 'errorText' => $error_message );
echo json_encode($return_data);

然后,您可以在javascript中使用它来显示消息:

function doSend_1_1() {
    $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_1', $('#input_1_1').serialize()).done(function(data) {
        $('#errorText_1_1').html(data.errorText);
    });
}

在一个如此简单的例子中,没有必要使用JSON——我们可以将文本发回。但希望它能展示如何根据需要发送更多数据。您在$return_data中输入的任何内容都将被发送到您的javascript.done函数。

尝试指定响应将以json形式出现,这样您就可以直接使用返回的数据:

function doSend_1_1() {
        $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_1_1', 
                $('#input_1_1').serialize(),
                function(data) {
                    $('#errorText_1_1').html(data.errorText);
                },
                'json' );
}