Client Side and Server Side
Client Side and Server Side
Here's a simple example that validates a form input on the client side using
JavaScript.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client-Side Scripting Example</title>
<script>
function validateForm() {
const name = document.getElementById("name").value;
if (name === "") {
alert("Name must be filled out");
return false; // Prevent form submission
}
alert("Form submitted successfully!");
return true; // Allow form submission
}
</script>
</head>
<body>
</body>
</html>
```
### Explanation:
- The form includes an input field for the user's name.
- The `validateForm` function checks if the name field is empty. If it is, an alert
is shown, and form submission is prevented.
- If the name is filled out, a success message is displayed, and the form can be
submitted.
---
```php
<!-- save this as form.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Server-Side Scripting Example</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize form data
$name = htmlspecialchars($_POST['name']);
echo "<h2>Welcome, $name!</h2>";
} else {
echo '<form method="post" action="form.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>';
}
?>
</body>
</html>
```
### Explanation:
- The PHP script checks if the form has been submitted using
`$_SERVER["REQUEST_METHOD"]`.
- If the form is submitted, it collects the input value, sanitizes it using
`htmlspecialchars` to prevent XSS attacks, and displays a welcome message.
- If the form hasn’t been submitted, it displays the form.
1. **Client-Side Script**:
- Save the client-side example in an HTML file (e.g., `client-side.html`).
- Open it in a web browser to test the form validation.
2. **Server-Side Script**:
- Save the PHP example in a file named `form.php`.
- Run a local server (e.g., using XAMPP, MAMP, or a built-in server with PHP).
- Access `form.php` through your web browser (e.g.,
`http://localhost/form.php`).
- Fill out the form and submit it to see the server response.