Ajax example with flask

One of the best ajax applied in real world is username checker. In this example we will check if there is existing username

This is code /project we will

  • use ajax to search username
  • if username exist or does not exist send to message to the user
  • Also create new user with html form and flask if username exists

Our first step: Check if username exists or not

Imagine we have this existing username

# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]

when the user enter a username we will check it from server(Check username)


@app.route('/check_username', methods=['POST'])
def check_username():
	username = request.form['username']
	print(username)
	if username in existing_usernames:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})
	elif not is_valid_username(username):
		return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
	else:
		return jsonify({'message': 'Username is available!'})


When new account is created username will be added to the username list (Create New User)


@app.route('/create_profile', methods=['POST'])
def create_profile():
	username = request.form['username']
	if username not in existing_usernames:
		existing_usernames.append(username)
		return  jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
	else:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})


In the client side we are using jquery to make everything simpler.

When the user will type it will automatically send to server with ajax and return the response

We will also make sure if the username exists the response text will show in green color if not it will show in red color.


$(document).ready(function () {
	$('#username').keyup(function () {
		var username = $(this).val();
		if (username.length === 0) {
			$('#usernameMessage').text("");
			return;
		}
		if (/\s/.test(username)) {
			$('#usernameMessage').text("Username cannot contain spaces.");
			return;
		}
		if (!/^[a-zA-Z0-9]+$/.test(username)) {
			$('#usernameMessage').text("Username cannot contain special characters.");
			return;
		}
		$.ajax({
			type: 'POST',
			url: '/check_username',
			data: { 'username': username },
			success: function (response) {
				$('#usernameMessage').text(response.message);
				if (response.message === 'Username is available!') {
					$('#usernameMessage').css('color', 'green');
				} else {
					$('#usernameMessage').css('color', 'red');
				}
			}
		});
	});




	$('#createProfileForm').submit(function (e) {
		e.preventDefault();
		var username = $('#username').val();
		if (username.length === 0) {
			$('#usernameMessage').text("Username cannot be empty.");
			return;
		}
		if (/\s/.test(username)) {
			$('#usernameMessage').text("Username cannot contain spaces.");
			return;
		}
		if (!/^[a-zA-Z0-9]+$/.test(username)) {
			$('#usernameMessage').text("Username cannot contain special characters.");
			return;
		}
		$.ajax({
			type: 'POST',
			url: '/create_profile',
			data: { 'username': username },
			success: function (response) {
				$('#usernameMessage').text(response.message);
			}
		});
	});
});



The complete code

structure

├── app.py
└── templates
    └── username-id-generate.html

The serverside code


import re
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Sample list of existing usernames
existing_usernames = ["user1", "user2", "user3"]


def is_valid_username(username):
	# Double check
	return re.match("^[a-zA-Z0-9_]*$", username) is not None


@app.route('/')
def index():
	return render_template('username-id-generate.html')


@app.route('/check_username', methods=['POST'])
def check_username():
	username = request.form['username']
	print(username)
	if username in existing_usernames:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})
	elif not is_valid_username(username):
		return jsonify({'message': 'Username contains special characters. Only letters, numbers, and underscores are allowed.'})
	else:
		return jsonify({'message': 'Username is available!'})


@app.route('/create_profile', methods=['POST'])
def create_profile():
	username = request.form['username']
	if username not in existing_usernames:
		existing_usernames.append(username)
		return  jsonify({'message': f"Welcome, {username}! Your profile has been created successfully."})
	else:
		return jsonify({'message': 'Username already exists! Please choose a different username.'})



if __name__ == '__main__':
	app.run(debug=True)



The client side code


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Profile</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            font-family: 'Helvetica Neue', sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        #createProfileForm {
            background: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 350px;
        }
        h1 {
            text-align: center;
            font-size: 28px;
            margin-bottom: 20px;
            color: #333;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
            font-size: 16px;
        }
        input[type="submit"] {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
        #usernameMessage {
            color: red;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <form id="createProfileForm">
        <h1>Create Your Profile</h1>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" autocomplete="off" required>
        <span id="usernameMessage"></span>
        <input type="submit" value="Create Profile">
    </form>
    <script>
        $(document).ready(function () {
            $('#username').keyup(function () {
                var username = $(this).val();
                if (username.length === 0) {
                    $('#usernameMessage').text("");
                    return;
                }
                if (/\s/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain spaces.");
                    return;
                }
                if (!/^[a-zA-Z0-9]+$/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain special characters.");
                    return;
                }
        $.ajax({
            type: 'POST',
            url: '/check_username',
            data: {'username': username},
            success: function (response) {
                $('#usernameMessage').text(response.message);
                if (response.message === 'Username is available!') {
                    $('#usernameMessage').css('color', 'green');
                } else {
                    $('#usernameMessage').css('color', 'red');
                }
            }
        });
    });

            $('#createProfileForm').submit(function (e) {
                e.preventDefault();
                var username = $('#username').val();
                if (username.length === 0) {
                    $('#usernameMessage').text("Username cannot be empty.");
                    return;
                }
                if (/\s/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain spaces.");
                    return;
                }
                if (!/^[a-zA-Z0-9]+$/.test(username)) {
                    $('#usernameMessage').text("Username cannot contain special characters.");
                    return;
                }
                $.ajax({
                    type: 'POST',
                    url: '/create_profile',
                    data: {'username': username},
                    success: function (response) {
                        $('#usernameMessage').text(response.message);
                    }
                });
            });
        });
    </script>
</body>
</html>



Get the project code from github

https://github.com/01one/flask-ajax-example