I'm new to AJAX and jQuery, and just for testing, I created this simple code. When the user enters their First Name and their Last Name it displays a message that says
Thanks for entering everything correctly!
in Bluish color, and when the user forgets to enter their First Name and their Last Name it displays an error that says
You didn't entered anything
in Red color or something similar. I know it sounds stupid, but this is just testing.
change_name.php
function displayError($error)
{
// Display a div with a class of error, We style it using CSS
echo "<div class='error'>$error</div><br>";
}
function displayMessage($message)
{
// Display a div with a class of message, We style it using CSS
echo "<div class='message'>$message</div> <br>";
}
if (isset($_POST['first_name']) && isset($_POST['last_name'])) {
if (empty($_POST['first_name']) && empty($_POST['last_name'])) {
displayError('You didn\'t entered anything!');
} else if (empty($_POST['first_name'])) {
displayError('You didn\'t entered your first name!');
} else if (empty($_POST['last_name'])) {
displayError('You didn\'t entered your last name!');
} else {
displayMessage('Thanks for entering everything correctly!');
}
}
JavaScript
$(document).ready(function(){
$('#nameChange').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'ajax/change_name.php',
data: $(this).serialize(),
success: function(data) {
$('.result').empty().append(data);
}
});
e.preventDefault();
});
});
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery AJAX</title>
<style>
.message {
font-family: sans-serif;
color: #00AAE9;
font-size: 16px;
}
.error {
font-family: sans-serif;
color: #E70000;
font-size: 16px;
}
</style>
</head>
<body>
<form action="ajax/change_name.php" method="POST" id="nameChange">
Result: <div class="result"></div>
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
<br>
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
<br>
<input type="submit" name="change_name" value="Change" id="change_name">
</form>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="js/init.js"></script>
</body>
</html>
Is it a good practice to display a <div>
and then add a class to it, so you can then style it using CSS? Is there a better way for doing this?