【问题标题】:Ajax process PHP form with different results from multiple conditionalsAjax 处理来自多个条件的不同结果的 PHP 表单
【发布时间】:2023-04-03 17:06:02
【问题描述】:

我现在有一个工作表单,它只使用条件来检查它是否已提交并在同一页面上处理表单:https://gist.github.com/adrianrodriguez/48cd90067a63691adc6a

但显然需要注意的是它会刷新页面。这实际上很好,我只是用一点点 JS 在表单与

相呼应后淡化结果
style="display:none"

这还不错……但我想为它增添趣味并使用 ajax。

下面是没有ajax的js(只是使用validation.js进行验证)

JS 已更新答案

$(document).ready(function(){
    // Jquery Form Functions
    $('#redeem').validate( { // initialize the plugin
        rules: {
            fullname: {
                required: true
            },
            cardnumber: {
                required: true,
                digits: true
            },
            email: {
                email: true,
                required: true
            },
            confirmation: {
                email: true,
                required: true,
                equalTo: "#email"
            }
        },
        invalidHandler: function (event, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = "<p>All fields in red must be filled*</p>";
                $("#redeem .message").html(message);
                $("#redeem .message").show();
                } else {
                    $("#redeem .message").hide();
                }
            },
            submitHandler: function (form) { // for demo
                //form.submit();

              $.ajax({
                url: form.action,
                type: form.method,
                data: $(form).serialize(),
                dataType: "json", // Recognize JSON Data
                success: function(data) {
                    $.each(data, function(key, value) {
                        // Loop with key and value from conditional
                        console.log(key + " " + value); 
                    });
                }
              });
              return false;
            }
        });

    if ($('.result')) {
        $('.result').fadeIn(400);
    }
});

我知道如何使用 ajax 进行处理:

$.ajax({
    url: form.action,
    type: form.method,
    data: $(form).serialize(),
    success: function(data) {
        console.log(data);
    }
});
return false;

它工作正常,但我遇到的问题是当我想根据表单中的一些条件回显特定字符串时。

A) 我无法回显信息,因为表单与处理它的页面是分开的...

B)...我不知道如何将该信息提取到正在处理的当前页面。

这甚至可能吗?如果是这样,怎么做?还是我只需要坚持我现在正在做的事情?

这是我现在工作的视频(没有 ajax):http://screencast.com/t/196P9ugso2L 并注意如果页面很长,它不会感觉表单正在被实时处理(而不是刷新)。就像我说的那样,老实说,我只是想提供更好的用户体验并增添趣味。

更新

带数组的 PHP(我认为我做错了,我尝试了三种不同的方法,都失败了 noob 风格)。

    <?php

include('db-connect.php');

$fullname = $_POST['fullname'];
$email = $_POST['email'];
$cardnumber = $_POST['cardnumber'];

$select = "SELECT * FROM cardholders WHERE cardnumber = $cardnumber";

$selectfrom = mysql_query($select);

if ($info = mysql_fetch_assoc($selectfrom)) {

    if ($fullname == $info['name'] && $info['used'] == 0) {

        // To send HTML mail, the Content-type header must be set
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        // $headers .= 'CC: $email' . "\r\n";
        $headers .= 'From: Comanche Nation Casinos <no-reply@comanchenationcasinos.com>';

        $confirmation = '<h1>Hi ' . $info['name'] . ' you\'ve won <b>$' . $info['amount'] . '</b> in Comanche Credit!</h1>
        <p>Thank you for being such a valuable C Club member. Print or Show this email and redeem this at your Comanche Nation Casino.</p>
        <p>Save this email just incase something happens so that the staff can ensure your reward at the kiosk.</p>';

        // mail("web@icgadv.com", "Care Center Gala Sponsorship Request", $staff, $headers);
        // mail($email, "Care Center Gala Sponsorship Request Confirmation", $confirmation, $headers);

        // $message = "<p>Congratulations!" . $info['name'] . "!</p> <p>You've won! Please check your email for your winnings and futher information.</p>";
        $winner = true;

        $message = array( 'winner' => true, 'message' => 'This is a test');

        $updateUser = "UPDATE cardholders SET email='$email', used=1 WHERE cardnumber = $cardnumber";

        $update = mysql_query($updateUser);

    } else if ($fullname != $info['name'] && $info['used'] == 0) {

        // $message = "Sorry but your name does not match the name in our database.";
        $noname = true;
        $message = array( 'winner' => true, 'message' => 'This is a test');

    } else {

        // $string = "<p>Sorry but this offer has already been redeemed to this account</p>";
        $redeemed = true;
        $message = array( 'winner' => true, 'message' => 'This is a test');

    }

    } else {
    // $message = array( 'status' => true, 'message' => "<p>Sorry but this card number    does not exist.</p>" );
    $invalid = true;
    $message = array( 'winner' => true, 'message' => 'This is a test');
    }

    echo json_encode($message);
?>

【问题讨论】:

  • 如果您使用 Ajax,为什么要在单独的页面上处理表单?我在您将数据提交到页面时读到,然后在您刚刚提交数据的页面上进行 Ajax 调用,对吗?
  • @Styphon,我不确定我是否理解你的问题。当我尝试通过 ajax 处理表单时,表单位于同一页面上,但它失败了。在以前的项目中,我的表单总是与处理它的页面分开并且工作正常。 (没有我要求的这个功能)
  • 好的,我现在明白了。 @TomToms 的答案是,虽然缺乏细节,但您正在寻找什么。

标签: php jquery ajax jquery-validate


【解决方案1】:

正如@TomToms 在上面发布的问题是您需要从调用的 Ajax 页面传回一个结果,即一次处理。如前所述,您使用 JSON 数组执行此操作。我将在下面给你一个简短的例子:

$.ajax({
    url: form.action,
    type: form.method,
    data: $(form).serialize(),
    dataType: "json",
    success: function(data) {
        console.log(data);
    }
});

注意添加的数据类型,这表明您期望返回一个 JSON 字符串,并将为您将其转换为 data 中的数组。

在您的处理页面上,form.action 您会看到:

// ... code that loads form information and all your current processing.
$example = array(
    'prize'    => true, // true or false on whether they get the prize.
    'status'   => 'Show Status Message' // put any message for the show status box here.
);

echo json_encode($example);

现在如果你在控制台最后查看data 将是一个包含奖品和状态的对象。

我还建议您查看JSON website 以了解有关 JSON 的更多信息。

【讨论】:

  • 必须是数组吗?难道只是 $string = 'String';回声 json_encode($string); ?
  • json_encode($string) 只会产生String。虽然你可以做到,但没有意义。 json_encode 的重点是将数组转换为字符串。你有两个需要更新的地方,你不能用一个字符串同时更新,因此你需要 JSON。
  • 感谢您到目前为止与我打交道,请继续原谅我对 JSON 的缺乏经验。我阅读了文档,然后阅读了其他一些 PHP 到 JSON 线程,并尝试了一些没有结果的事情。我想知道我是否只是做错了。我是否需要将条件转换为数组,然后使用 json_encode 回显消息?
  • 是的,这就是您需要做的。如果您这样做后仍然难以解决,请使用 Ajax 页面中的代码更新您的原始问题,我会进一步帮助您。
  • 我已经更新了原始问题,我认为我最大的障碍是弄清楚如何将我的条件变成一个数组。
【解决方案2】:

如果我正确理解您的问题,您需要发回一个 JSON 数组,其中包含每个字段的状态代码或类似内容,然后在您的 javascript 中对其进行解析以适当地警告用户。

【讨论】:

  • 您能否详细说明一些可能的代码示例?我以前没有接触过 JSON,可以使用一些指导。
【解决方案3】:

As per documentation、.ajax() 总是在 submitHandler 回调函数内部。

替换这个...

submitHandler: function (form) {  // fires on submit when form is valid  
    form.submit();  // regular submit action
}

有了这样的东西……

submitHandler: function (form) {  // fires on submit when form is valid 
    $.ajax({
        url: $(form).action,
        type: $(form).method,
        data: $(form).serialize(),
        success: function(data) {
            console.log(data);
        }
    });
    return false;  // block the default form action
}

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2010-12-21
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多