0% found this document useful (0 votes)
3 views17 pages

Web Technology Unit- (4)

The document provides a comprehensive overview of AJAX (Asynchronous JavaScript and XML), detailing its features, workings, and applications in web development using PHP and MySQL. It explains how AJAX enhances user experience by allowing asynchronous communication, real-time updates, and faster responses without page reloads. Additionally, it includes practical examples and code snippets for implementing AJAX with PHP for tasks such as live search and form submissions.

Uploaded by

agnirahul11a43
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)
3 views17 pages

Web Technology Unit- (4)

The document provides a comprehensive overview of AJAX (Asynchronous JavaScript and XML), detailing its features, workings, and applications in web development using PHP and MySQL. It explains how AJAX enhances user experience by allowing asynchronous communication, real-time updates, and faster responses without page reloads. Additionally, it includes practical examples and code snippets for implementing AJAX with PHP for tasks such as live search and form submissions.

Uploaded by

agnirahul11a43
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/ 17

INDEX

Focus S No. Title S No.


1. AJAX with PHP
2. PHP Code and the Complete AJAX Example
3. AJAX Database
4. Working of AJAX live search with PHP
AJAX 5. Ajax PHP Database Form
6. AJAX PHP MySQL Database
7. Connect, create DB
8. Create table, insert data, select query
Q: What is AJAX? Explain its features and working with a suitable example using PHP. Also mention
where AJAX is used in web development.
Answer:
AJAX stands for Asynchronous JavaScript and XML. It is a technology used to send and receive data from a
server without reloading the web page. This makes the web page more interactive and faster because only a
part of the page updates instead of the whole page.
AJAX is not a programming language. It is a technique that uses a combination of the following:
 HTML and CSS for page structure and style
 JavaScript to make requests and handle responses
 The XMLHttpRequest object to send and receive data
 PHP (or any server-side language) to process data
Features of AJAX:

1. Asynchronous communication: AJAX allows data exchange with the server in the background. The
user can continue interacting with the page while the data loads.

2. No page refresh: With AJAX, parts of the page can be updated without a full reload. This saves time
and bandwidth.

3. Faster response: AJAX makes websites faster because only small parts of the data are sent or received,
not the entire page.

4. Uses plain JavaScript and XMLHttpRequest: AJAX mostly uses the built-in XMLHttpRequest object
in JavaScript.

5. Can use multiple data formats: Although the name has "XML" in it, AJAX can work with XML,
JSON, HTML, or plain text.
How AJAX works:

The basic working of AJAX can be explained in the following steps:


1. A user does something on the webpage (like typing in a search box).
2. JavaScript captures this event and creates an XMLHttpRequest object.
3. This object sends a request to a PHP file on the server.
4. The PHP file performs some operation, like checking a database.
5. PHP sends back a response (data).
6. JavaScript receives the response and updates the web page without a refresh.

Conclusion:

AJAX is a very useful technique that improves user experience by making websites fast and dynamic. It reduces
page reloads and helps in building real-time features using JavaScript and PHP. Even though new frameworks
are popular now, AJAX is still used in the background of many web applications
► Ajax Database
AJAX with Database using PHP:
AJAX is used to send and receive data from the server without reloading the page. When used with a database, it
helps fetch or update data in real-time.
How it works:
1. User types something or performs an action.
2. JavaScript sends an AJAX request to a PHP file.
3. PHP connects to the database and runs a query.
4. The result is sent back to JavaScript.
5. Page updates automatically, without refresh.
Example: Live Search
If we type a name in a search box, AJAX sends that name to PHP. PHP searches the database for matching
names and returns them. AJAX shows them live on the page.
Benefits:
 No page reload
 Faster user experience
 Real-time results
So, AJAX with a database is useful for features like live search, real-time updates, auto-suggestions, and more.

► AJAX Live Search using PHP


HTML:

<input type="text" id="search" onkeyup="searchUser()">


<div id="result"></div>

JavaScript:

function searchUser() {
let input = document.getElementById("search").value;
let xhr = new XMLHttpRequest();
xhr.open("GET", "search.php?q=" + input, true);
xhr.onload = function() {
if (xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}
PHP (search.php):

$q = $_GET['q'];
$conn = mysqli_connect("localhost", "root", "", "mydb");

$sql = "SELECT name FROM users WHERE name LIKE '%$q%'";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . "<br>";
}
} else {
echo "No results found";
}

Uses of AJAX in Web Development:

AJAX is widely used in modern web development. Some common uses are:

1. Live Search – Like Google instant search results.


2. Form Submission – Submitting forms without reloading the page.
3. Chat Applications – Sending and receiving messages instantly.
4. Auto-refresh Data – Like live scores, stock updates, etc.
5. Loading Comments or Notifications – Without page reload.

► AJAX PHP Database Form:


An AJAX PHP Database Form is a form on a web page that saves data to a database using PHP and AJAX
without reloading the page.
🛠 How it works:
1. The user fills the form and clicks submit.
2. JavaScript (AJAX) takes the form data.
3. AJAX sends the data to a PHP file.
4. PHP connects to the database and stores the data.
5. PHP sends back a response like “Data saved successfully.”
6. AJAX shows that response on the page without refreshing it.
✅ Example:
HTML + JavaScript:
<form id="myForm">
Name: <input type="text" id="name"><br>
Email: <input type="text" id="email"><br>
<button type="button" onclick="submitForm()">Submit</button>
</form>

<div id="response"></div>

<script>
function submitForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;

let xhr = new XMLHttpRequest();


xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onload = function () {
document.getElementById("response").innerHTML = xhr.responseText;
};

xhr.send("name=" + name + "&email=" + email);


}
</script>

PHP (submit.php):
<?php
$name = $_POST['name'];
$email = $_POST['email'];

$conn = mysqli_connect("localhost", "root", "", "formdb");


$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $sql)) {
echo "Data saved successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
?>

SQL for Table:


CREATE DATABASE formdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Benefits:
 No page reload when submitting form.
 Fast and user-friendly experience.
 Helps in real-time data handling.

► AJAX PHP MySQL Database:


AJAX with PHP and MySQL allows dynamic interaction with the database. Using AJAX, we can send
requests to PHP scripts, which then communicate with a MySQL database to retrieve, update, or delete data,
and return the results back to the webpage without refreshing the entire page.

How it Works:
1. AJAX Request is triggered from JavaScript (for example, a user action like typing or clicking a button).
2. The AJAX request sends data (like a search query or form input) to a PHP file.
3. PHP connects to the MySQL database and performs a query (e.g., SELECT, INSERT, UPDATE).
4. The PHP file returns the result (like new records or confirmation) to the JavaScript.
5. JavaScript dynamically updates the webpage using the received data, without needing a page reload.
Example: AJAX PHP MySQL Search (Live Search)
This is a common example where we use AJAX with PHP and MySQL to search for data (e.g., users' names)
from a database.

HTML + JavaScript (index.html):


<input type="text" id="search" onkeyup="searchUser()">
<div id="result"></div>

<script>
function searchUser() {
let input = document.getElementById("search").value;

let xhr = new XMLHttpRequest();


xhr.open("GET", "search.php?q=" + input, true);
xhr.onload = function() {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.send();
}
</script>
PHP (search.php):
<?php
$q = $_GET['q'];

$conn = mysqli_connect("localhost", "root", "", "userdb");

$sql = "SELECT name FROM users WHERE name LIKE '%$q%'";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . "<br>";
}
} else {
echo "No results found.";
}
?>
MySQL Table Setup:
CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);

INSERT INTO users (name) VALUES ('Rahul'), ('Ravi'), ('Rita'), ('Reena');


Explanation of Code:
1. HTML: Contains a text input field where users can type. The onkeyup event calls the
searchUser() function every time the user types.
2. JavaScript: The searchUser() function sends an AJAX GET request to the search.php file
with the user input as a parameter (q).
3. PHP: The search.php file gets the q parameter from the URL, connects to the MySQL database,
and runs a SELECT query to find matching names. If names are found, they are displayed. Otherwise,
it shows “No results found.”
4. MySQL: A simple database and table users are created to store names for searching.
Conclusion:
AJAX, combined with PHP and MySQL, helps in creating interactive web applications. It allows dynamic
updates like live search, form submission, and real-time updates by sending requests to the server without
reloading the whole page. This makes web applications faster and more user-friendly.

► Q: Explain how to connect to a MySQL database using PHP. Create a database, create a table,
insert data, and run a SELECT query.

1. Connect to MySQL Database Using PHP:


To connect to a MySQL database using PHP, you use the mysqli_connect() function. This function
establishes a connection between your PHP script and the MySQL server.
Example:s
<?php
// Connection to the MySQL server
$conn = mysqli_connect("localhost", "root", "", "testdb");

// Check the connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
 Parameters:
 "localhost": Host (usually localhost for local server).
 "root": Username (default MySQL username is root).
 "": Password (empty by default in XAMPP/MAMP).
 "testdb": Name of the database you want to connect to.

2. Create a Database Using PHP:


To create a database, you can use the CREATE DATABASE SQL command. You execute it using the
mysqli_query() function.
Example:
<?php
// Connect to the MySQL server
$conn = mysqli_connect("localhost", "root", "");

// Check if the connection is successful


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create a new database


$sql = "CREATE DATABASE testdb";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>

3. Create a Table in the Database:


Once the database is created, you can create tables inside it. You define the structure (columns and types) using
SQL.
Example:
<?php
// Connect to the MySQL server and the database
$conn = mysqli_connect("localhost", "root", "", "testdb");

// Check the connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// SQL query to create a table


$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100),
reg_date TIMESTAMP
)";

// Execute the query


if (mysqli_query($conn, $sql)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

// Close the connection


mysqli_close($conn);
?>

4. Insert Data into the Table:


To insert data into a table, use the INSERT INTO SQL query.
Example:
<?php
// Connect to the MySQL server and the database
$conn = mysqli_connect("localhost", "root", "", "testdb");

// Check the connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Insert data into the 'users' table


$sql = "INSERT INTO users (name, email) VALUES ('Rahul', '[email protected]')";

// Execute the query


if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . mysqli_error($conn);
}

// Close the connection


mysqli_close($conn);
?>

5. SELECT Data from the Table:


To fetch data from the table, you use the SELECT SQL query. The data is returned by the mysqli_query()
function, and then you can fetch it using mysqli_fetch_assoc().
Example:
<?php
// Connect to the MySQL server and the database
$conn = mysqli_connect("localhost", "root", "", "testdb");

// Check the connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// SQL query to select all records from the 'users' table


$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);

// Check if any rows are returned


if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "0 results";
}

// Close the connection


mysqli_close($conn);
?>

Conclusion:
 Connect: Use mysqli_connect() to connect to the MySQL server.
 Create Database: Use CREATE DATABASE to create a new database.
 Create Table: Define table structure and use CREATE TABLE SQL query.
 Insert Data: Use INSERT INTO to add data to the table.
 Select Data: Use SELECT to retrieve data from the table.
This is how we interact with a MySQL database using PHP—connecting, creating databases and tables,
inserting, and fetching data.

Questions that might be asked in your Web Technologies exam:


1. Define AJAX and explain its role in web development.
Expected Answer:
AJAX (Asynchronous JavaScript and XML) is a technique used in web development to create dynamic and
interactive user interfaces. It allows web pages to update asynchronously by exchanging small amounts of data
with the server behind the scenes, without reloading the entire page.
Key Points:
 Asynchronous Communication: Enables the browser to send and receive data asynchronously,
improving user experience.
 Data Formats: Initially used XML, but now commonly uses JSON due to its lightweight nature.
 Technologies Involved: JavaScript, XMLHttpRequest (or Fetch API), and server-side languages like
PHP.

2. How does AJAX improve user experience in web applications?


Expected Answer:
AJAX enhances user experience by:
 Reducing Page Load Time: Only necessary data is fetched and updated, rather than reloading the entire
page.
 Providing Real-Time Updates: Enables features like live search, notifications, and auto-suggestions.
 Improving Interactivity: Allows for smooth user interactions without interruptions.

3. Write a PHP script to connect to a MySQL database and fetch data using AJAX.
Expected Answer:
HTML + JavaScript (index.html):
<input type="text" id="search" onkeyup="searchUser()">
<div id="result"></div>

<script>
function searchUser() {
let input = document.getElementById("search").value;

let xhr = new XMLHttpRequest();


xhr.open("GET", "search.php?q=" + input, true);
xhr.onload = function() {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.send();
}
</script>
PHP (search.php):
<?php
$q = $_GET['q'];

$conn = mysqli_connect("localhost", "root", "", "userdb");

$sql = "SELECT name FROM users WHERE name LIKE '%$q%'";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . "<br>";
}
} else {
echo "No results found.";
}
?>
MySQL Table Setup:
CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);

INSERT INTO users (name) VALUES ('Rahul'), ('Ravi'), ('Rita'), ('Reena');


4. Discuss the advantages and disadvantages of using AJAX in web development.
Expected Answer:
Advantages:
 Improved User Experience: Provides faster interactions by updating parts of a page without a full
reload.
 Reduced Server Load: Only necessary data is exchanged, reducing bandwidth usage.
 Enhanced Interactivity: Facilitates features like live search, form validation, and real-time updates.
Disadvantages:
 SEO Challenges: Content loaded via AJAX may not be indexed by search engines.
 Browser Compatibility: Older browsers may not fully support AJAX.
 Complex Debugging: Asynchronous nature can make debugging more challenging.

5. Explain the role of JSON in AJAX applications.


Expected Answer:
JSON (JavaScript Object Notation) is a lightweight data-interchange format commonly used in AJAX
applications due to:
 Ease of Use: Easily parsed and generated by JavaScript.
 Human-Readable: Simple syntax makes it easy to read and write.
 Compatibility: Supported by most modern programming languages.
In AJAX, JSON is often used to exchange data between the client and server, replacing XML due to its
simplicity and efficiency.

6. Create a simple AJAX-based form submission using PHP and MySQL.


Expected Answer:
HTML + JavaScript (form.html):
<form id="myForm">
Name: <input type="text" id="name"><br>
Email: <input type="text" id="email"><br>
<button type="button" onclick="submitForm()">Submit</button>
</form>

<div id="response"></div>

<script>
function submitForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;

let xhr = new XMLHttpRequest();


xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onload = function () {
document.getElementById("response").innerHTML = xhr.responseText;
};

xhr.send("name=" + name + "&email=" + email);


}
</script>
PHP (submit.php):

<?php
$name = $_POST['name'];
$email = $_POST['email'];

$conn = mysqli_connect("localhost", "root", "", "formdb");

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";


if (mysqli_query($conn, $sql)) {
echo "Data saved successfully.";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
MySQL Table Setup:
CREATE DATABASE formdb;

USE formdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);

7. What are the key differences between synchronous and asynchronous requests in AJAX?
Expected Answer:

Feature Synchronous Request Asynchronous Request


Blocks code execution until response is Does not block code execution;
Execution
received continues running
User
Can freeze UI until response is received Provides a smoother user experience
Experience
Suitable for operations where subsequent Ideal for operations that can run
Use Case
code depends on the response independently of other code

You might also like