You are on page 1of 14

Unit_V Programming in PHP ACAS

Unit-V
1. Ajax
a. Getting started with ajax
b. Writing Ajax
c. Creating the XMLHttpRequest Object
d. Opening the XMLHttpRequest Object
e. Downloading Data using Ajax
f. Passing Data to server with GET
g. Passing Data to server with POST

2. Advanced Ajax
a. Handling Concurrent Ajax Requests
b. Downloading Images using Ajax
c. Getting data with Head Requests and Ajax

3. Drawing Images on the server


a. Creating an Image
b. Displaying Images in HTML pages
c. Drawing Line
d. Drawings Rectangle
e. Drawing Arcs
f. Drawing Ellipses
g. Drawing Polygons
h. Copying Images
i. Drawing Text

1. Ajax

a. Getting Started with Ajax:


 Definition: Ajax (Asynchronous JavaScript and XML) is a technique that allows you
to update parts of a web page without requiring a full page reload.
b. Writing Ajax:
 Definition: Writing Ajax involves using JavaScript to make asynchronous requests to
a server and update the page dynamically based on the response.
c. Creating the XMLHttpRequest Object:
 Definition: The XMLHttpRequest object is a fundamental part of Ajax. It provides
the ability to send and receive data between a client and server without requiring a full
page refresh.
var xhr = new XMLHttpRequest();
 Explanation: In this program, you create a new instance of the XMLHttpRequest
object using the constructor.
d. Opening the XMLHttpRequest Object:

1
Unit_V Programming in PHP ACAS

 Definition: Opening the XMLHttpRequest involves specifying the type of request


(GET, POST, etc.) and the target URL.
 Example Program:
xhr.open("GET", "data.php", true);
 Explanation: This program uses the open() method to set up a GET request to the
"data.php" URL. The third parameter true indicates that the request should be
asynchronous.
e. Downloading Data using Ajax:
 Definition: Downloading data using Ajax involves sending a request to the server and
handling the response.
 Example Program:
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = xhr.responseText;
document.getElementById("result").innerHTML = response;
}
};
 Explanation: This program sets up an event handler using the onreadystatechange
property. When the state changes to 4 (request complete) and the status is 200 (OK), it
retrieves the response using xhr.responseText and updates the "result" element on
the page.
f. Passing Data to Server with GET:
 Definition: Passing data to the server using GET involves appending data to the URL
as query parameters.
 Example:
<!DOCTYPE html>
<html>
<head>
<title>Ajax GET Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Ajax GET Example</h2>

2
Unit_V Programming in PHP ACAS

<button id="fetchData">Fetch Data</button>


<div id="output"></div>

<script>
$(document).ready(function() {
$("#fetchData").click(function() {
$.ajax({
url: "server.php", // URL of the server-side script
method: "GET", // HTTP method
data: { key: "value" }, // Data to send to the server
success: function(response) {
$("#output").html(response); // Display server response
}
});
});
});
</script>
</body>
</html>
In this example, the client-side HTML page uses jQuery for handling the Ajax request.
Here's how the program works:
1. When the "Fetch Data" button is clicked, the JavaScript code initiates an Ajax request
to the server.
2. The $.ajax() function sends a GET request to the server-side script "server.php". You
need to replace this with the actual URL of your server-side script.
3. The data parameter in the $.ajax() function allows you to send data to the server. In
this case, we're sending a key-value pair.
4. If the request is successful, the success callback function is executed. It receives the
server's response as the response parameter.
5. The response is then displayed inside the <div> element with the id "output".
server.php (server-side script):
<?php

3
Unit_V Programming in PHP ACAS

if (isset($_GET['key'])) {
$value = $_GET['key'];
echo "Received value: " . $value;
} else {
echo "No data received.";
}
?>
In the server-side script, you check if the GET parameter "key" is set. If it is, you retrieve
its value and send a response to the client.
g. Passing Data to Server with POST:
 Definition: Passing data to the server using POST involves sending data as part of the
request body.
 Example:
index.html (client-side HTML file):
<!DOCTYPE html>
<html>
<head>
<title>Ajax POST Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Ajax POST Example</h2>
<button id="postData">Post Data</button>
<div id="output"></div>

<script>
$(document).ready(function() {
$("#postData").click(function() {
$.ajax({
url: "server.php", // URL of the server-side script
method: "POST", // HTTP method

4
Unit_V Programming in PHP ACAS

data: { key: "value" }, // Data to send to the server


success: function(response) {
$("#output").html(response); // Display server response
}
});
});
});
</script>
</body>
</html>
server.php (server-side script):
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['key'])) {
$value = $_POST['key'];
echo "Received value: " . $value;
} else {
echo "No data received.";
}
?>

In this example, the client-side HTML page and the server-side PHP script are similar to the
previous example, with the only difference being the HTTP method used is POST.
The $.ajax() function's method parameter is set to "POST", and the data is sent to the server
using the POST method. On the server side, you check
$_SERVER["REQUEST_METHOD"] to ensure the request is a POST request, and then
you retrieve the POST parameter "key" and send a response to the client.
When you open the HTML file in a browser and click the "Post Data" button, the data is sent
to the server using the POST method, and the server's response is displayed on the page.

2.Advanced Ajax
a. Handling Concurrent Ajax Requests:

5
Unit_V Programming in PHP ACAS

 Definition: Handling concurrent Ajax requests involves managing multiple


asynchronous requests to the server simultaneously.
Handling concurrent Ajax requests involves managing multiple asynchronous requests to the
server simultaneously. Here's an example of how you can use PHP to handle concurrent Ajax
requests on the server-side:

server.php (server-side PHP script):


<?php
if (isset($_GET['request'])) {
$request = $_GET['request'];

if ($request === 'request1') {


// Simulate a delay for request 1
sleep(2);
echo "Response for Request 1";
} elseif ($request === 'request2') {
// Simulate a delay for request 2
sleep(1);
echo "Response for Request 2";
} else {
echo "Invalid request";
}
}
?>
index.html (client-side HTML and JavaScript):

<!DOCTYPE html>
<html>
<head>
<title>Concurrent Ajax Requests</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

6
Unit_V Programming in PHP ACAS

<body>
<h2>Concurrent Ajax Requests</h2>
<button id="sendRequest1">Send Request 1</button>
<button id="sendRequest2">Send Request 2</button>
<div id="output1"></div>
<div id="output2"></div>

<script>
$(document).ready(function() {
$("#sendRequest1").click(function() {
sendAjaxRequest('request1', 'output1');
});

$("#sendRequest2").click(function() {
sendAjaxRequest('request2', 'output2');
});

function sendAjaxRequest(requestType, outputElement) {


$.ajax({
url: "server.php",
method: "GET",
data: { request: requestType },
success: function(response) {
$("#" + outputElement).html(response);
}
});
}
});
</script>
</body>

7
Unit_V Programming in PHP ACAS

</html>
In this example, the client-side HTML page contains two buttons that allow you to send
concurrent Ajax requests to the server. When you click the "Send Request 1" button, it sends
a request for "request1," and when you click the "Send Request 2" button, it sends a request
for "request2."
The server-side PHP script (server.php) simulates delays for each request using the sleep()
function to demonstrate the concurrent nature of the requests.
When you click the buttons, you'll notice that the responses appear in the respective output
divs as soon as they are ready. This showcases how the server can handle multiple requests
simultaneously, and the browser can display the results as they become available.
Remember to have both files (server.php and index.html) in the same directory when testing
this example.
b. Downloading Images using Ajax:
 Definition: Downloading images using Ajax involves fetching image data from the
server and displaying it on the web page.
 Example Program:
$(document).ready(function() {
$("#loadImage").click(function() {
$.ajax({
url: "image.jpg", // URL of the image
method: "GET",
responseType: "blob", // Set response type to blob
success: function(response) {
var url = URL.createObjectURL(response);
$("#output").html("<img src='" + url + "' alt='Downloaded Image'>");
}
});
});
});
 Explanation: This program uses Ajax to fetch an image named "image.jpg". The
responseType is set to "blob" to handle binary data. When the image is successfully
received, it's converted to a blob URL using URL.createObjectURL(), and the
image is displayed on the page.
c. Getting Data with Head Requests and Ajax:

8
Unit_V Programming in PHP ACAS

 Definition: Using HEAD requests with Ajax allows you to retrieve metadata about a
resource without fetching the entire resource.
 Example Program:
$(document).ready(function() {
$("#getHeaders").click(function() {
$.ajax({
url: "resource.txt", // URL of the resource
method: "HEAD", // Use HEAD request
success: function(data, textStatus, xhr) {
var headers = xhr.getAllResponseHeaders();
$("#output").html("<pre>" + headers + "</pre>");
}
});
});
});
 Explanation: This program sends a HEAD request to fetch headers from a resource
named "resource.txt". When the request is successful, the getAllResponseHeaders()
method of the xhr object is used to get the response headers, and they are displayed
on the page.
Advanced Ajax techniques involve handling multiple requests concurrently, working with
different response types (like images), and using HEAD requests to fetch headers. These
techniques enhance the functionality and capabilities of Ajax-powered applications.

3. Drawing Images on the server


a. Creating an Image
b. Displaying Images in HTML pages
c. Drawing Line
d. Drawings Rectangle
e. Drawing Arcs
f. Drawing Ellipses
g. Drawing Polygons

9
Unit_V Programming in PHP ACAS

h. Copying Images
i. Drawing Text

a. Creating an Image:
 Definition: Creating an image involves generating a new image canvas or loading an
existing image file that can be further modified using various drawing functions.
 Example Program:
<?php
$width = 400;
$height = 300;
$image = imagecreatetruecolor($width, $height);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $backgroundColor);
imagepng($image, 'new_image.png');
imagedestroy($image);
?>
 Explanation: This program creates a new true-color image canvas with the specified
dimensions. It fills the canvas with a white background and then saves the image as
"new_image.png".
b. Displaying Images in HTML Pages:
 Definition: Displaying images in HTML pages involves using the <img> tag to
embed and show images on a web page.
 Example Program:
<html>
<head>
<title>Displaying Images</title>
</head>
<body>
<img src="new_image.png" alt="New Image">
</body>
</html>

10
Unit_V Programming in PHP ACAS

 Explanation: This HTML page uses the <img> tag to display the previously created
image ("new_image.png") on the web page.
c. Drawing Lines:
 Definition: Drawing lines involves creating straight lines on an image canvas using
specific coordinates.
 Example Program
<?php
$image = imagecreatefrompng('new_image.png');
$lineColor = imagecolorallocate($image, 0, 0, 255);
imageline($image, 50, 50, 200, 100, $lineColor);
imagepng($image, 'new_image_with_line.png');
imagedestroy($image);
?>
 Explanation: This program loads the previously created image, draws a blue line
from (50, 50) to (200, 100), and saves the modified image as
"new_image_with_line.png".
d. Drawing Rectangles:
 Definition: Drawing rectangles involves creating rectangular shapes on an image
canvas using specific coordinates
 Example Program
<?php
$image = imagecreatefrompng('new_image.png');
$rectangleColor = imagecolorallocate($image, 255, 0, 0);
imagerectangle($image, 100, 150, 300, 250, $rectangleColor);
imagepng($image, 'new_image_with_rectangle.png');
imagedestroy($image);
?>
 Explanation: This program loads the image, draws a red rectangle with top-left
corner at (100, 150) and bottom-right corner at (300, 250), and saves the modified
image as "new_image_with_rectangle.png".
e. Drawing Arcs:
 Definition: Drawing arcs involves creating curved lines or segments of circles on an
image canvas using specific coordinates and angles.

11
Unit_V Programming in PHP ACAS

 Example Program
<?php
$image = imagecreatefrompng('new_image.png');
$arcColor = imagecolorallocate($image, 0, 255, 0);
imagearc($image, 250, 200, 200, 150, 0, 180, $arcColor);
imagepng($image, 'new_image_with_arc.png');
imagedestroy($image);
?>
 Explanation: This program loads the image, draws a green arc centered at (250, 200)
with a width of 200 pixels and a height of 150 pixels, covering an angle of 180
degrees, and saves the modified image as "new_image_with_arc.png".
f. Drawing Ellipses:
 Definition: Drawing ellipses involves creating elliptical shapes on an image canvas
using specific coordinates and dimensions.
 Example Program
<?php
$image = imagecreatefrompng('new_image.png');
$ellipseColor = imagecolorallocate($image, 255, 255, 0);
imageellipse($image, 300, 150, 200, 100, $ellipseColor);
imagepng($image, 'new_image_with_ellipse.png');
imagedestroy($image);
?>
 Explanation: This program loads the image, draws a yellow ellipse centered at (300,
150) with a width of 200 pixels and a height of 100 pixels, and saves the modified
image as "new_image_with_ellipse.png".
g. Drawing Polygons:
 Definition: Drawing polygons involves creating multi-sided shapes on an image
canvas using specific sets of coordinates.
 Example Program:
<?php
$image = imagecreatefrompng('new_image.png');
$polygonColor = imagecolorallocate($image, 0, 255, 255);

12
Unit_V Programming in PHP ACAS

$points = array(300, 50, 500, 100, 400, 200, 250, 150);


imagepolygon($image, $points, 4, $polygonColor);
imagepng($image, 'new_image_with_polygon.png');
imagedestroy($image);
?>

h. Copying Images:
 Definition: Copying images involves duplicating or copying the content of one image
onto another image canvas.
Example
<?php
$sourceImage = imagecreatefrompng('source_image.png');
$destinationImage = imagecreatetruecolor(600, 400);

imagecopy($destinationImage, $sourceImage, 100, 100, 0, 0, imagesx($sourceImage),


imagesy($sourceImage));

imagepng($destinationImage, 'copied_image.png');
imagedestroy($sourceImage);
imagedestroy($destinationImage);
echo "Image copied and saved as 'copied_image.png'.";
?>
 Explanation: This program creates a new image canvas and copies the content of a
source image onto the destination image using imagecopy(). The source image is
specified by imagecreatefrompng() and the positions and dimensions of the copy are
provided as arguments.
i. Drawing Text:
 Definition: Drawing text involves adding text onto an image canvas using specific
font, size, color, and positioning.
<?php
$image = imagecreatetruecolor(600, 400);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);

13
Unit_V Programming in PHP ACAS

imagefill($image, 0, 0, $backgroundColor);

$textColor = imagecolorallocate($image, 0, 0, 0);


$font = 'arial.ttf';
$text = 'Hello, PHP!';
imagettftext($image, 24, 0, 200, 200, $textColor, $font, $text);

imagepng($image, 'image_with_text.png');
imagedestroy($image);
echo "Image with text drawn and saved as 'image_with_text.png'.";
?>
Explanation: This program creates a new image canvas, fills it with a white
background, allocates a color for the text, specifies a font file (arial.ttf), defines the
text to be displayed, and uses imagettftext() to draw the text on the image. The
resulting image will have the specified text rendered on it.

14

You might also like