elliott.david 2016-06-04 09:31 采纳率: 25%
浏览 15

返回上一个功能

I'm using ajax to check if a username is taken. If the username is taken it returns false to the form submit function. I'm using MySQL.

index.php

$("#register-form").submit(function(){
    var un = $("#un").val();
    $.ajax({
        type: "GET",
        url: "user_check.php",
        dataType: "html",
        data: {un: un},
        success: function(data){

        }
    });
});

user_check.php

$db = mysqli_connect("localhost","root","","webcap");
$user = $_POST['un'];
$query = mysqli_query($db,"SELECT * FROM users WHERE username='$un'");
$count = mysqli_num_rows($query);
echo $count;

How I return false to the register form submit function if data is 1 or true if it's 0? Is there an easier way to do this?

  • 写回答

2条回答 默认 最新

  • weixin_33725239 2016-06-04 09:35
    关注

    Use JSON. In the PHP do:

    echo json_encode($count > 0);
    

    And in the Javascript, specify type: 'json' instead of type: 'html'. Then data will be true or false.

    However, since AJAX is asynchronous, you can't return a value from this.

    What you need to do is prevent normal form submission in the .submit() function. Then in the success: function, check the response and submit the form if it was successful.

    $("#register-form").submit(function(e){
        e.preventDefault();
        var un = $("#un").val();
        $.ajax({
            type: "GET",
            url: "user_check.php",
            dataType: "json",
            data: {un: un},
            success: function(data){
                if (data) {
                    $("#register-form")[0].submit(); // really submit the form
                } else {
                    alert("Username is taken");
                }
            }
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app