简体   繁体   中英

JQuery Ajax Request With PHP Validation

I saw this code somewhere without the PHP backend for it and have wondering how to recreate the PHP to validate my forms using this code:

$('input.signup-input[name=username]').blur(function () {
    var input = $('input.signup-input[name=username]');
    var validation = input.parent().parent().children('td.validation');
    $.post("/validate.php", {
        cmd: "verify-username",
        username: input.val()
    }, function (data) {
        if (data == 'success') {
            validation.html('<div class="success"></div>');
            input.removeClass('error-input');
        } else {
            validation.html('<div class="error">' + data.error + '</div>');
            input.addClass('error-input');
        }
    }, 'json');
});

In my PHP would I just $_POST a verify-username variable and then echo success if the field passes validation?

And if the field encounters an error would I have to json_encode an error variable in PHP so that it can be put into the data.error location of this jquery?

Anyone have any suggestions on what I should do?

Your approach is right. Just a note though... you don't have to use json since you are simply passing text and validating it. You can use the simple text/html method. Json is used when you use arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM