javascript - Username verification if already exists in the database using PHP CodeIgniter, JQuery, AJAX - Stack Overflow

I am trying to check the username's validity first before the user hits the submit button using Co

I am trying to check the username's validity first before the user hits the submit button using Codeigniter. The status of the username if it is taken or not will just appear beside it.

Here is the JS in the view:

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript"><!--
 $(document).ready(function() {
    $("#username").blur(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax


        $.post("addpatient/check_user_availability",{ username:$(this).val() } ,function(data) {
            if(data=='no') {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });

            }
            else {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                });
            }
        });

    });

});  
</script>


Here is a part of the form in html:

<form method="post" action="addpatient/insert" name="register">
        <table id='addpatient'>
            <tr>    
                <td width=100> Username:
                <td width=150>  <input type='text' id='username' name='username' value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" placeholder="5-15 char" pattern=".{5,15}" required>
                <td> <span id="msgbox" style="display:none"></span>
                <td><div id="msgbox"></div>
            </tr>...


Here is the controller:

function check_user_availability()
    {
        $username = $this->input->post('username');

        //  Developed by Roshan Bhattarai 
        //  Visit  for this script and more.
        //  This notice MUST stay intact for legal use


        //this varible contains the array of existing users
        $existing_users=$this->user->get_all_usernames();
        //value got from the get metho
        $user_name= $username;

        //checking weather user exists or not in $existing_users array
        if (in_array($user_name, $existing_users))
        {
            //user name is not availble
            echo "no";
        } 
        else
        {
            //user name is available
            echo "yes";
        }
    }


And this is a function in the model:

function get_all_usernames() {
    $this->db->select('username');
    $this->db->from('users');
    $query = $this->db->get();
    return $query->result();
 }



However, when I run it, it always says that the username is available to register even though the username has been taken already.

Another problem is that it doesn't check the username's validity as the user types in his/her desired username in "real time". What I mean is, the user has to click on the next textfields first before the code checks the validity.

Please help me solve these problems. Thank you!

I am trying to check the username's validity first before the user hits the submit button using Codeigniter. The status of the username if it is taken or not will just appear beside it.

Here is the JS in the view:

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript"><!--
 $(document).ready(function() {
    $("#username").blur(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax


        $.post("addpatient/check_user_availability",{ username:$(this).val() } ,function(data) {
            if(data=='no') {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });

            }
            else {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                });
            }
        });

    });

});  
</script>


Here is a part of the form in html:

<form method="post" action="addpatient/insert" name="register">
        <table id='addpatient'>
            <tr>    
                <td width=100> Username:
                <td width=150>  <input type='text' id='username' name='username' value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" placeholder="5-15 char" pattern=".{5,15}" required>
                <td> <span id="msgbox" style="display:none"></span>
                <td><div id="msgbox"></div>
            </tr>...


Here is the controller:

function check_user_availability()
    {
        $username = $this->input->post('username');

        //  Developed by Roshan Bhattarai 
        //  Visit http://roshanbh..np for this script and more.
        //  This notice MUST stay intact for legal use


        //this varible contains the array of existing users
        $existing_users=$this->user->get_all_usernames();
        //value got from the get metho
        $user_name= $username;

        //checking weather user exists or not in $existing_users array
        if (in_array($user_name, $existing_users))
        {
            //user name is not availble
            echo "no";
        } 
        else
        {
            //user name is available
            echo "yes";
        }
    }


And this is a function in the model:

function get_all_usernames() {
    $this->db->select('username');
    $this->db->from('users');
    $query = $this->db->get();
    return $query->result();
 }



However, when I run it, it always says that the username is available to register even though the username has been taken already.

Another problem is that it doesn't check the username's validity as the user types in his/her desired username in "real time". What I mean is, the user has to click on the next textfields first before the code checks the validity.

Please help me solve these problems. Thank you!

Share Improve this question edited Sep 14, 2013 at 2:07 Fionnlagh Endika asked Sep 14, 2013 at 2:00 Fionnlagh EndikaFionnlagh Endika 31 gold badge2 silver badges5 bronze badges 4
  • are you sure $query->result() is an array and not an object? Perhaps you should be returning a result_array(): ellislab./codeigniter/user-guide/database/results.html – Kai Qing Commented Sep 14, 2013 at 2:15
  • Thanks for that! So I tried $query->result_array() but it still says the username is valid all the time. I tried to plug in sample values of the array $existing_users=array('john','jack','carol'); and when I typed these in the textfield, it still says such usernames are valid. – Fionnlagh Endika Commented Sep 14, 2013 at 2:20
  • if you console.log(data) in your success does it give you the expected literal string? You are only checking for 'no' so if anything else is being returned it will say it is available. Including any white spaces or other things that may be passed as the script executes – Kai Qing Commented Sep 14, 2013 at 2:41
  • Following Nil'z's answer, the console prints a yes. – Fionnlagh Endika Commented Sep 14, 2013 at 3:01
Add a ment  | 

2 Answers 2

Reset to default 1

Try this:

function check_user_availability()
{
    $username   = $this->input->post('username');
    $result     = $this->user->get_all_usernames( $username );  #send the post variable to the model
    //value got from the get metho
    $user_name= $username;

    if( $result ){
        echo "no";
    }else{
        echo "yes";
    }
}

function get_all_usernames( $username ) {
    $this->db->select('username');
    $this->db->where('username', $username)
    $this->db->from('users', 1);
    $query = $this->db->get();
    if( $query->num_rows() > 0 ){
        return 0;
    }else{
        return 1;
    }
}

Changes in the script:

$(document).ready(function() {
    $("#username").keyup(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax

        var name    = $(this).val();
        $.ajax({
            url     : "<?=base_url()?>addpatient/check_user_availability",
            data    : { username : name },
            type    : 'POST',
            success : function(data){
                if( data == '0' ){
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                        //add message and change the class of the box and start fading
                        $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                    });
                }else if( data == '1' ){
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                        //add message and change the class of the box and start fading
                        $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                    });
                }else{
                    alert("Some error occured! Check Console");
                }
            }
        });
    });
}); 

Controller:

function check_user_availability() {
    $username = $this->input->post('username');

    $this->form_validation->set_rules('username', 'Username', 'required|is_unique[users.username]');

    if ($this->form_validation->run() == FALSE) {
        //user name is not availble
        echo "no";
    } else {
        //user name is available
        echo "yes";
    }
}

Replace your check_user_availability() in controller with above. no need of using your get_all_usernames model.

View documentation for Form_Validation, set_rules

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745210124a4616788.html

相关推荐

  • 边玩边学:黑群晖使用Docker搭建超级玛丽游戏服务器支持远程访问

    前言在数字时代,我们每天长时间面对电脑屏幕,处理工作、浏览文件,生活节奏越来越快。下班后,你是否也怀念起童年时光,想起那些拿着游戏机,沉浸在游戏世界中的快乐?那种简单的快乐,现在似乎很难再体验到了。别担心!今天就来教你一个有趣的方法——在黑

    53分钟前
    00
  • 初识Redis · list和hash类型

    前言:前文我们已经介绍了string的基本使用,以及对应的基本命令,最后也是简单的理解了一下string的应用场景,比如计数统计器啊,比如作为缓存的存放常用的数据啊什么的,当然也有通过设置key的过期时间,然后整个分布式锁什么的。以上是对s

    50分钟前
    00
  • 算法训练之贪心

    前置知识在真正开始贪心算法题目练习之前,我们首先要了解什么是贪心算法?贪心算法有什么特点?什么是贪心算法? 我们可以用一句话来概括:贪婪+鼠目寸光贪心策略: 解决问题的策略,由局部最优——>全局最优具体步骤

    46分钟前
    00
  • 数字人:开启医疗领域的智慧变革新时代(510)

    摘要:数字人技术作为医疗变革的基石,通过多学科融合实现虚拟医生、手术模拟、医学教育等多元应用,贯穿诊前、术中、术后全流程,显著提升医疗效率、优化资源分配、推动个性化服务。尽管面临技术、伦理、数据安全等挑战,数字人未来有望与人工智能、虚拟现

    44分钟前
    00
  • 思维与算法共舞:AIGC语言模型的艺术与科学

    正文开始——引言:AIGC与文本生成概述人工智能生成内容(AIGC)是指通过使用机器学习算法,尤其是深度学习模型,来自动生成各种类型的内容,包括文字、图像、音频和视频等。文本生成是AIGC最常见且应用最广泛的领域之一。在过去的几年里,随着自

    43分钟前
    00
  • SpringBoot条件注解全解析:核心作用与使用场景详解

    引言 Spring Boot 的条件注解(Conditional Annotations)是自动配置(Auto-Configuration)的核心机制之一。它们允许开发者根据特定的条件动态决定是否加载某个Bean或配置类,从而实现灵活的“按

    35分钟前
    00
  • Windows单语言版显示语言限制解析与专业版升级指南

    Windows单语言版显示语言限制解析与专业版升级指南 现象解析:为何系统仅支持单一显示语言? 当用户收到"Windows许可证仅支持一个显示语言"的提示时,这表明当前系统为Windows 10家庭单语言版。该版本是

    35分钟前
    10
  • AnyBurn 制作ISO

    #西里网# 下载安装AnyBurn访问AnyBurn官网下载最新版本运行安装程序,按向导完成安装启动AnyBurn双击桌面快捷方式或从开始菜单启动程序选择创建ISO功能在主界面点击"创建ISO文件"按钮或通过菜单&quo

    29分钟前
    00
  • [c语言日寄]时间复杂度

    前言在C语言的编程实践中,时间复杂度是一个至关重要的概念。它不仅反馈了程序的运行效率,还直接决定了代码在处理大规模数据时的可行性。今天,我们就通过一个简单的程序来深入探讨时间复杂度的计算方法、分析技巧以及优化策略,帮助大家更好地理解和应用这

    27分钟前
    00
  • 安装文档:SecureCRT安装使用

    *SecureCRT**使用* 第1章 CRT安装 l 步骤1&#xff1a;安装“scrt_sfx731-x86.exe” l 步骤2&#xff1a;欢迎页面 l 步骤3&#xff1a;如果是64位操作系统&a

    23分钟前
    00
  • 【GitHub精选】开源免费!一键生成宫崎骏动画风,这个神器比GPT

    项目背景:当AI遇见吉卜力,一场艺术与技术的碰撞吉卜力工作室的动画以唯美画风、细腻情感和奇幻场景闻名,但想用AI复刻这种风格却难如登天。最近,一个名为EasyControl的开源项目横空出世,号称能“一键生成吉卜力风”,效果甚至媲美GPT-

    17分钟前
    00
  • Deepseek本地部署 + 个性化 Rag 知识库

    什么是 RAG ? Retrieval-Augmented Generation (RAG) 是一种结合了信息检索与文本生成的先进模型架构,旨在提高自然语言处理任务中的准确性和相关性。不同于传统的端到端生成模型,RAG 通过整合外部知识库来

    15分钟前
    00
  • 2025蓝桥杯JavaB组真题解析

    本次蓝桥杯除了几个延期的省份之外,其他的省份都是结束了的,下面的这个是我针对于蓝桥杯JavaB组的文字解析,仅供参考 ,方法不唯一,我也出了对应的视频解析,依照自己的理解进行说明,大家可以选择性观看;视频观看方式在评论区自取;1.第一题

    14分钟前
    00
  • 免费教学Windows Server评估版永久转换为数据中心版攻略

    哈喽大家好,欢迎来到虚拟化时代君(XNHCYL),收不到通知请将我点击星标!“ 大家好,我是虚拟化时代君,一位潜心于互联网的技术宅男。这里每天为你分享各种你感兴趣的技术、教程、软件、资源、福利…(每天更新不间断,福利不见不散) 第一章、

    13分钟前
    00
  • TypeScript 基础语法入门指南

    TypeScript 是 JavaScript 的超集,通过静态类型检查和丰富的语法特性,帮助开发者编写更健壮、可维护的代码。本文将从零开始介绍 TypeScript 的基本语法,帮助你快速掌握核心概念。类型注解(Type Annotati

    12分钟前
    00
  • 【随笔】解决 dynamic

    前言最近在开发一个 Spring Boot 项目时,遇到了嵌入式 Tomcat 启动失败的问题,错误日志指向 dynamic-datasource的主数据源配置问题。经过一番排查,发现是 dynamic-datasource 2.5.6

    9分钟前
    00
  • EmEditor 强大而简单易用的Windows文本编辑器

    EmEditor是日本的江村软件公司&#xff08;Emurasoft&#xff09;所开发的一款在Windows平台上运行的文字编辑程式。EmEditor以运作轻巧、敏捷而又功能强大、丰富著称&#xff0c;得到许

    8分钟前
    00
  • 一个死锁导致的invalid connection问题排查

    1. 背景上周社区业务的开发同学反馈他负责的Go应用请求Mysql时不时会报错invalid connection,一直排查不到原因,因此我帮他排查了下,最终发现是一个比较典型的死锁问题,因此记录下排查过程与思路。首先看下监控报错:imag

    8分钟前
    00
  • 【HarmonyOS 5】AttributeModifier和AttributeUpdater详解

    【HarmonyOS 5】AttributeModifier和AttributeUpdater区别详解一、AttributeModifier和AttributeUpdater的定义和作用1. AttributeModifier是ArkUI组

    5分钟前
    00
  • 我的技术管理探索之路(ppt)

    该ppt记录自己的技术管理上走过的坑和一些成长心得(2008~2022年),2023~至今仍在积累沉淀中,期待有更大的突破,未来再做分享。本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。原始发表:2025-03-12,如有侵权请联系 

    59秒前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信