Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Jquery and ajax, my function for username checking?
- function check_username() {
- var username = $("#username").val();
- $('.loading').fadeIn().delay(100);
- $.post("ajax.php", {
- username: $('#username').val(),
- }, function (response) {
- $('.error, .success').hide();
- setTimeout(function () {
- $('.loading').hide();
- finishAjax('username', response);
- }, 1000);
- });
- return false;
- }
- function finishAjax(id, response) {
- $('#' + id).after(response).fadeIn(1000);
- }
- <?php
- require('dbc.php');
- if (isset($_REQUEST['username'])) {
- $q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
- $q -> execute(array($_REQUEST['username']));
- if (strlen($_REQUEST['username']) < 3) {
- echo '<div class="error">Has to be at least 3 characters</div>';
- }
- elseif ($q -> rowCount() > 0) {
- echo '<div class="error">Username already taken</div>';
- }
- else {
- echo '<div class="success">Username available</div>';
- }
- }
- ?>
- $.fn.checkValid = function(options)
- {
- var response = function(response) {
- var setClass = '';
- var $span = $(this).data('checkValidTip');
- if ($span)
- {
- $span.remove();
- }
- if (response === undefined) return;
- setClass = (response.valid ? 'valid' : 'invalid');
- var $span = $('<span>' + response.msg + '</span>');
- $(this)
- .data('checkValidTip', $span)
- .after($span);
- $span.hide()
- .fadeIn(1000)[0]
- .className = setClass;
- };
- var ajaxOptions = {
- type: 'GET',
- url: 'ajax.php',
- success: response,
- dataType: 'json'
- };
- this.each(function() {
- var that = this;
- var ajaxRequest = ajaxOptions;
- ajaxRequest.data = {};
- ajaxRequest.data[options.key] = this.value;
- ajaxRequest.context = that
- $.ajax(ajaxRequest);
- });
- };
- $('#username, #email').blur(function() {
- $(this).checkValid({ key: this.id });
- });
- <?php
- // Do your sql statements here, decide if input is valid or not
- $arr = array('valid' => $is_valid,
- 'msg' => $error_or_good_msg
- );
- echo json_encode($arr);
- /* For example will output:
- {
- "valid": "false",
- "msg": "<b>Error: Must be at least 2 characters</b>"
- }
- Which can be read directly as response.valid
- or response.msg from within response() function
- */
- var validations = {
- username: {
- min_chars: 4,
- max_chars: 10,
- valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
- },
- email: {
- regex: /./ //your magic regex here
- }
- };
Add Comment
Please, Sign In to add comment