检索已通过ajax处理的数据

时间:2016-05-18 10:39:19

标签: php jquery mysql ajax

我有一个jquery移动调查表。

第一个问题是使用{单选按钮}

询问参加者的性别

当用户点击性别单选按钮,并且女性数量等于100时,我希望该表单被禁用。

我已经完成了连接到mysql数据库的php并计算了女性参与者的数量,并且效果非常好。但是,当用户点击性别单选按钮时,如何使用ajax动态连接到php脚本并显示php脚本的结果。

请帮助我。php code that checks database

3 个答案:

答案 0 :(得分:1)

您可以在单选按钮上添加change事件的代码并将ajax代码放入其中,这样,如果您的php ajax有一些结果,您可以相应地制定条件。

PS:用于更改单选按钮类而不是id,因为每个单选按钮可以具有单独的id。如果您使用相同的ID,则只会使用第一个ID来检查数据。

答案 1 :(得分:1)

请注意,此代码未经过测试,我刚刚编写它仅用于演示:

这个JS脚本主要检查所选单选按钮是否为女性,然后通过post发送检查标志到php文件。

在你的php文件中你应该检查女人的总人数是否已经是100;然后返回一个“超出”类型的消息,该消息将在脚本中捕获,因此您可以添加所需的操作,例如隐藏表单和添加自定义消息。

JS:

<script type="text/javascript">
    $('form input[name=female]').on('change', function () {
        if ($('input[name=female]:checked', 'form').val() == "female") {
            var loader = jQuery('#loader');
            loader.fadeIn();
            //add aditional post values values here
            post_data = {
                'check': '1'
            };
            $.post('processing.php', post_data, function (response) {
                if (response.type == "exceeded") {
                    $('#message').html(response.text);
                    $("#message").fadeIn();
                    loader.fadeOut();
                    //Do more actions here like:
                    $('form').slideUp();
                }
            }, 'json');
        }
    });
</script>

<强> processing.php

<?php
if ($_POST) {
    //check if its an ajax request, exit if not
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        $output = json_encode(array(//create JSON data
            'type' => 'error',
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    }

    $check = filter_var($_POST["check"], FILTER_SANITIZE_NUMBER_INT);
    if ($check) {
        //check the total nbr of women saved in the database and add it to $total_women
        if ($total_women >= 100) {
            $output = json_encode(array('type' => 'exceeded', 'text' => 'Max nbr reached'));
            die($output);
        }
    }
}
?>

干杯!

答案 2 :(得分:0)

如果你在php服务器端回应任何东西它重新调整ajax成功

所以你的ajax应该抓住它,像这样显示给用户

success: function(data) {

       //data is what you echoed in php server side like enough participant like this 

       alert(data); //just alert message or you should append it with html
    }