5. Java Script & JQuery
5. Java Script & JQuery
<script>
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
}
</script>
In this example, the form won't submit if the name field is empty,
and an alert will appear.
4. Introduction to jQuery
jQuery is a fast, small, and feature-rich JavaScript library. It simplifies
tasks like HTML document traversal, event handling, animation, and
Ajax interactions. It allows you to do things with fewer lines of code
compared to vanilla JavaScript.
Basic Syntax:
$(document).ready(function() {
// Your code here
});
Here, $(document).ready() ensures that the JavaScript runs only after
the HTML document has finished loading.
<script>
$("#myForm").submit(function(e) {
e.preventDefault(); // Prevent form submission
var name = $("#fname").val();
if (name == "") {
alert("Name must be filled out");
} else {
alert("Form submitted");
}
});
</script>
In this example, the form will not submit unless the "Name" field is
filled out.
6. jQuery Forms
jQuery can also be used to handle form submissions, Ajax, and
dynamically modify form elements.
Example of jQuery AJAX Form Submission:
<form id="myForm">
Name: <input type="text" id="fname">
<input type="submit" value="Submit">
</form>
<script>
$("#myForm").submit(function(e) {
e.preventDefault(); // Prevent form submission
var name = $("#fname").val();
$.ajax({
url: "submit_form.php",
type: "POST",
data: { fname: name },
success: function(response) {
alert("Form submitted successfully!");
}
});
});
</script>
In this example, the form will submit the data asynchronously to
submit_form.php using Ajax, without reloading the page.
7. jQuery Examples
Hide and Show Elements:
$("#hideButton").click(function() {
$("#content").hide(); // Hide the element with id "content"
});
$("#showButton").click(function() {
$("#content").show(); // Show the element with id "content"
});
Animating Elements:
$("#animateButton").click(function() {
$("#content").animate({
width: "toggle"
});
});
Changing CSS Properties:
$("#changeColorButton").click(function() {
$("#content").css("color", "red"); // Change text color to red
});
Adding/Removing Classes:
$("#addClassButton").click(function() {
$("#content").addClass("highlight");
});
$("#removeClassButton").click(function() {
$("#content").removeClass("highlight");
});
1. Introduction to AJAX
What is AJAX? AJAX is a technique that combines JavaScript,
XML (or JSON), and HTML to make asynchronous requests to
the server.
How does AJAX work?
o The client-side JavaScript sends an HTTP request to the
server.
o The server processes the request, often by interacting
with a database, and sends back data (usually in JSON or
XML format).
o JavaScript on the client side processes and displays the
returned data without refreshing the page.
Basic Example:
// JavaScript to send an AJAX request
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "server_script.php", true);
xhttp.send();
<script>
function sendData() {
let name = document.getElementById("name").value;
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-
form-urlencoded");
xhttp.send("name=" + name);
}
</script>
PHP (process.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
echo "Hello, " . htmlspecialchars($name);
}
?>
In this example:
JavaScript captures the user input and sends it to process.php
via an AJAX POST request.
PHP script processes the data and returns a response, which is
displayed on the webpage without a refresh.
3. Working with Database Using PHP and AJAX
AJAX is commonly used with PHP to interact with databases for
creating interactive and data-driven web applications.
Example: Fetching Data from a Database with AJAX
HTML + JavaScript (AJAX request):
<button onclick="fetchData()">Get Users</button>
<div id="users"></div>
<script>
function fetchData() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("users").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "fetch_users.php", true);
xhttp.send();
}
</script>
PHP (fetch_users.php):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " .
$row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In this example:
When the button is clicked, fetchData() sends an AJAX GET
request to fetch_users.php.
The PHP script connects to the database, retrieves data from
the "users" table, and returns it as HTML.
The response is displayed within the #users div on the web
page.
<script>
function updateUser() {
let username = document.getElementById("username").value;
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("updateStatus").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "update_user.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-
form-urlencoded");
xhttp.send("username=" + username);
}
</script>
PHP (update_user.php):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$sql = "UPDATE users SET username='$username' WHERE id=1";