检查ID,然后使用ajax,codeigniter

时间:2016-11-26 15:49:04

标签: php ajax codeigniter

我有一个表单包含1个文本框和一个消息标签,用于查看患者的信息。用户将输入文本框并点击"输入",如果输入为空或不可用id,系统将返回消息标签:"未找到!再试一次...",如果输入是可用ID,则重定向到查看患者页面。 我的代码无效,不显示错误消息,也不会重定向。

这是我的控制人员:



public function checkID()
    {
        require 'application/config/database.php';
        $id = isset($_POST['id']) ? $_POST['id'] : false;

        $conn = mysqli_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password'], $db['default']['database'])
        or die ('{error:"bad_request"}');
        $query = mysqli_query($conn, 'select count(*) as count from patient where PID = \"'.  addslashes($id).'"');

        $error = array(
            'error' => 'Success'
        );

        if (!$id){
            $error['error'] = 'Not Found! Try again...';
            die ('{error:"bad_request"}');
        }

        if ($query){
            $row = mysqli_fetch_array($query, MYSQLI_ASSOC);
            if ((int)$row['count'] == 0){
                $error['error'] = 'Not Found! Try again...';
            }
            elseif ((int)$row['count'] > 1) {
                $error['error'] = 'Not Found! Try again...';
            }
        }

        die (json_encode($error));
    }




这是我的ajax功能:



function checkSearchText(e, obj) {
    var reg = /[\<\>\.\'\"\:\;\|\{\}\[\]\,\=\+\-\_\!\~\`\(\)\$\#\@\^\&\,\?]/;
    if (String(obj.value).match(reg)) {
        obj.value = '';
    }
    if ((e.which == 13)) {
        // var res =
        $.ajax({
            url: "checkID",
            global: false,
            type: "POST",
            async: false,
            data: {
                id: id
            },
            success: function (result) {
                if($.trim(result.error) != '' && $.trim(result.error) != 'Not Found! Try again...') {
                    self.document.location = 'view/' + obj.value;
                }
                else {
                    $('#errmsg').append(result.error);
                    $('#errmsg').style = 'color: #FF0000';
                }

            }
        });
    }
}
&#13;
&#13;
&#13; 这是我的表格:

&#13;
&#13;
<form method='post' action>";
    <input class='input' placeholder='Eg.44531' type='text' autofocus id='id' name='id' onkeyup=checkSearchText(event,this);>
    <div id='errmsg' >Type Patient ID and hit ENTER</div>";
</form>";
&#13;
&#13;
&#13;

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

那么如果您正在使用CodeIgniter,为什么不使用表单验证类和其他功能?

在您的控制器中:

public function checkID(){
    $this->load->helper('form');
    $this->load->library('form_validation');

    $this->form_validation->set_rules('id', 'Patient ID', 'callback_check_id');

    if ($this->form_validation->run() === FALSE){
        $this-load->view('myForm');
    }else{
        // CI does all the work for form validation
        // Validation runs so you can redirect
    }
}

// Callback function to check ID
public function check_id($id)
{
    if (/*$id does not exist in database*/){
        $this->form_validation->set_message('check_id', 'Not Found! Try again...');
        return FALSE;
    }else{
        return TRUE;
    }
}

和您的视图文件(在控制器中称为“myForm”):

<?php
$id = array(
    'name'  => 'id',
    'id'    => 'id',
    'value' => set_value('id'),
    'type'  => 'text',
    'class' => 'input',
    'placeholder' => 'Eg.44531',
);
?>

<?php echo form_open('yourController/checkID'); ?>
    <?php echo form_input($id); ?>
    <?php echo form_error($id['name']); ?><?php echo isset($errors[$id['name']])?$errors[$id['name']]:''; ?>
    <?php echo form_submit('submit', 'Lets check this ID'); ?>
<?php echo form_close(); ?>

代码片段来自我的头脑,没有经过测试,您必须添加查询以检查数据库中的ID存在(建议使用CI query builder

为了更好地理解代码段的工作原理CodeIgniter form validation libraryCodeIgniter Form Helper