0% found this document useful (0 votes)
1 views

5. Java Script & JQuery

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

5. Java Script & JQuery

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

5.

Java Script & JQuery


1. Introduction to JavaScript
JavaScript is a lightweight, interpreted programming language
primarily used for creating dynamic and interactive effects within
web browsers. It is a client-side scripting language, meaning it runs in
the user's browser rather than the server.
Three Ways to Use JavaScript:
 Inline JavaScript: You can place JavaScript directly inside HTML
tags.
<button onclick="alert('Hello World!')">Click Me</button>
 Internal JavaScript: You can place JavaScript code inside the
<script> tag within the HTML document.
<script>
function greet() {
alert('Hello World!');
}
</script>
<button onclick="greet()">Click Me</button>
 External JavaScript: You can write JavaScript in an external file
and link it to your HTML file.
<script src="script.js"></script>
Inside script.js:
function greet() {
alert('Hello World!');
}
2. Working with Events in JavaScript
JavaScript provides a way to interact with users through events such
as clicks, mouse movements, keyboard inputs, etc.
Event Handling:
 Click Event:
<button onclick="alert('Button Clicked!')">Click Me</button>
 Mouseover Event: Triggered when the mouse hovers over an
element.
<p onmouseover="this.style.color='red'">Hover over me to change
color</p>
 Keyboard Event: Triggered when a key is pressed.
<input type="text" onkeydown="alert('Key pressed!')">
 Using addEventListener:
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button clicked!");
});

3. Client-side Validation in JavaScript


Client-side validation is used to check input fields before sending data
to the server. This helps improve user experience by catching errors
before the server processes them.
Example of Client-side Validation:
<form name="myForm" onsubmit="return validateForm()">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

<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.

5. Validation Using jQuery


jQuery simplifies form validation with built-in functions. You can
validate forms using event handlers and jQuery's built-in methods.
Example of jQuery Form Validation:
<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();
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");
});

6. Connecting Forms using AJAX Concept


AJAX (Asynchronous JavaScript and XML) allows you to update parts
of a web page without reloading the entire page. It uses JavaScript to
send and receive data asynchronously with the server, making web
applications faster and more dynamic.

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();

2. PHP with AJAX


AJAX can be combined with PHP to create dynamic, database-driven
applications. PHP scripts can be called via AJAX to interact with a
database, retrieve or update data, and send back the result in real
time.
Example: Using AJAX with PHP
HTML + JavaScript (AJAX request):
<input type="text" id="name" placeholder="Enter your name">
<button onclick="sendData()">Submit</button>
<div id="result"></div>

<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);
}

$sql = "SELECT id, name, email FROM users";


$result = $conn->query($sql);

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.

4. Updating Database Records with AJAX


AJAX can also be used to update records in a database without page
reloads.
HTML + JavaScript (AJAX request):
<input type="text" id="username" placeholder="Enter new
username">
<button onclick="updateUser()">Update</button>
<div id="updateStatus"></div>

<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";

if ($conn->query($sql) === TRUE) {


echo "Username updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
In this example:
 The AJAX call sends the new username to update_user.php.
 The PHP script updates the "username" in the database, and a
success message is returned and displayed without page reload.

You might also like