如何在另一个函数中使用各种ajax请求的结果?

时间:2014-07-12 02:53:14

标签: javascript php jquery ajax forms

我一直在使用ajax验证编写注册表单。我设置它的方式是在我的js文件中,我有听众,当字段的内容被更改时触发。他们将数据发送到服务器,服务器确保它有效,并以json对象的形式发回它的响应。然后我读取json对象的值以输出潜在的错误消息。

我不会复制和粘贴整个文件,只是一个例子:

$(document).ready(function() {
    // USERNAME VALIDATION LISTENER

    $("#regUsername").change(checkName);
}

然后checkName函数看起来像这样,它发送我的ajax请求:

function checkName() {
    $.ajax({
        type: "POST",
        url: "./ajax_register.php",
        data: {
            request: "nameAvail",
            username: $("#regUsername").val()
        },
        success: function(data) { // execute on success
            var json = jQuery.parseJSON(data);

            if (json.success) { // if usernames do match
                $("#usernameAvailiability").removeClass().addClass('match');
                $("#usernameAvailiability").text(json.msg);  
            } else { // if the user has failed to match names
                $("#usernameAvailiability").removeClass().addClass('nomatch');
                $("#usernameAvailiability").text(json.msg);
            }
        }
    });
}

根据响应,它会更新一个跨度,告诉用户他们写的输入是否有效。 服务器验证这部分php文件:

if(!isset($_POST['request'])) { // do nothing if no request was provided
    print("no request provided");
} else { //ELSE request has been provided
    if ($_POST['request'] == "nameAvail") { // if the request is to check if the username is valid
    $response = array("success" => false, "msg" => " ", "request" => "nameAvail");

    // CHECK USER NAME AVAILIABILITY CODE

    if (!isset($_POST['username']) || empty($_POST['username'])) { // if no username is entered
        $response['success'] = false;
        $response['msg'] = "No username provided";
    } else { // if a username has been entered
        $username = $dbConn->real_escape_string($_POST['username']);

        if (!ctype_alnum($username)) { // Make sure it's alpha/numeric
            $response['success'] = false;
            $response['msg'] = "username may only contain alpha numeric characters";
        } elseif (strlen($username) < 4) { // make sure it's greater than 3 characters
            $response['success'] = false;
            $response['msg'] = "username must be at least 4 characters long.";
        } elseif (strlen($username) > 20) { // make sure it's less than 26 characters
            $response['success'] = false;
            $response['msg'] = "username can be up to 20 characters long.";
        } else { // make sure it's not already in use
            $query = $dbConn->query("SELECT `id`, `username` FROM `users` WHERE `username` = '"
                    . $username . "' LIMIT 1");

            if ($query->num_rows) { // if the query returned a row, the username is taken
                $response['success'] = false;
                $response['msg'] = "That username is already taken.";
            } else { // No one has that username!
                $response['success'] = true;
                $response['msg'] = "That username is availiable!";
            }
        }
    }
    print(json_encode($response));
}

我现在要做的是在我的javascript中为注册按钮创建一个函数。但我需要确保首先验证所有表格。

我不确定我的选择是什么。我想要做的是以某种方式能够回收我已经在我的php文件中编写的代码。我不想写出全新的if($ _ POST ['request'] ==“register”)子句,然后复制并粘贴所有验证代码,以确保在我将注册人数据插入之前输入有效数据库。这看起来真的很重复!

我知道我可以查看页面上的所有跨度是否都设置为“匹配”,但这很容易被篡改,并且可以提交空白表单。

到目前为止,我的注册按钮功能如下所示:

function register() { 
    if ( NEED SOME KIND OF CLAUSE HERE TO CHECK IF ALL THE FIELDS ARE VALID) {

    $.ajax({
        type: "POST",
        url: "./ajax_register.php",
        data: {
            request: "register",
            username: $("#regUsername").val(),
            password: $("#regPassword").val(),
            email: $("#email").val(),
            dob: $("#dob").val(),
            sQuest: $("#securityQuestion").val(),
            sAns: $("#securityAnswer").val(),
            ref: $("#referred").val()
        }, success: function(data) {
            var json = jQuery.parseJSON(data);
            console.log(json);

            $("#regValid").removeClass();
            $("#regValid").text("");
        }
    }); //AJAX req done

} else {
    $("#regValid").removeClass().addClass('nomatch');
    $("#regValid").text("One or more fields are not entered correctly");
}
return false;// so that it wont submit form / refresh page
}

我真的很感激一些帮助,我花了最近几个小时来搜索stackoverflow以获得答案,但我似乎无法得到任何工作。我是否必须在我的php文件中复制代码,或者是否有更优雅的方法来处理它?<​​/ p>

0 个答案:

没有答案