首页 > 解决方案 > 在模式窗口中发送表单

问题描述

对不起,我开始这个话题。我知道这件事有很多话题。但我仍然无法处理它,因为我需要将成功/失败消息显示如下:

<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="submit" name="save-test-form" value="Save">
</form>

/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
    if(!empty($_POST['name'])){
        if(!empty($_POST['email'])){
            $_SESSION['success_msg'] = 'All is well.';
        }else{
            $_SESSION['error_msg'] = 'Enter the email.';
        }
    }else{
        $_SESSION['error_msg'] = 'Enter the name.';
    }
}
?>

And jquery?

我的意思是在不重新加载页面的情况下提交此表单(因为它位于模式窗口中),并且我必须在表单中显示成功/失败消息(也无需重新加载页面)。我不知道怎么做。

我将不胜感激如何一步一步地提供帮助和解释。

标签: phpjquery

解决方案


您的 PHP 脚本在页面重新加载时执行,因此在使用 Ajax 时,您必须手动显示来自服务器的消息:

// PHP

$response = [];

if(isset($_POST['save-test-form'])){
    if(!empty($_POST['name'])){
        if(!empty($_POST['email'])){
            $response['success'] = 'All is well.';
        }else{
            $response['error_msg'] = 'Enter the email.';
        }
    }else{
        $response['error_msg'] = 'Enter the name.';
    }

    echo json_encode($response); // Format array as json and output it
    die(); // No other output, just JSON
}

// jQuery

$.ajax({
    url: '',
    method: 'POST',
    dataType: 'json',
    data: {},
    success: function (response) {
        if (typeof response.success !== 'undefined') {
            $('#responseMessage').text(response.success);
        } else {
            $('#responseMessage').text(response.error_msg);
        }
    }
})

推荐阅读