labook wt 2
labook wt 2
LABCOURSE III
SECTION I
Web Technologies II
SEMESTER-II
Name
College Name
Academic Year
BOARD OF STUDIES
Co-ordinators
PREPARED BY
Prof. Shaikh A.M. H.P.T. Arts & R.Y.K. Science College, Nashik
Prof. Malani P.S. K.K.Wagh Arts,Commerce,Science & Computer Science College, Nashik
Page2 T.Y.B.Sc.(Comp.Sc.)Lab-III,Sem-II
Objectives –
2 Incomplete 1
3 Late complete 2
4 Needs improvement 3
5 Complete 4
6 Well-done 5
Page3 T.Y.B.Sc.(Comp.Sc.)Lab-III,Sem-II
1. Explain the assignment and related concepts in around ten minutes using white board if
required or by demonstrating the software.
6. The value should also be entered on assignment completion page of respected lab
course.
Page4 T.Y.B.Sc.(Comp.Sc.)Lab-III,Sem-II
PHP Semester – II
4 AJAX
Total out of 25
Total out of 05
University Exam Seat Number__________ has successfully completed the course work for CS - 368
Page5 T.Y.B.Sc.(Comp.Sc.)Lab-III,Sem-II
PHP Cookies
Cookie is a small piece of information stored as a file in the user's browser by the web server. Once created,
cookie is sent to the web server as header information with every HTTP request.
User can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.
1. To store user information like when he/she visited, what pages were visited on the website etc, so that
next time the user visits your website you can provide a better user experience.
2. To store basic website specific information to know this is not the first visit of user.
3. You can use cookies to store number of visits or view counter.
Types of Cookies
There are two types of cookies :
1. Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the
browser is closed.
2. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time. Then the
cookie will only expire after the given expiration time, until then it will be a valid cookie.
syntax :
setcookie(name, value, expire, path, domain, secure)
The first argument which defines the name of the cookie is mandatory, rest all are optional arguments.
name Used to specify the name of the cookie. It is a mandatory argument. Name of the
cookie must be a string.
value Used to store any value in the cookie. It is generally saved as a pair with name. For
example, name is userid and value is 7007, the userid for any user.
expire Used to set the expiration time for a cookie. if you do not provide any value, the
cookie will be treated as a session cookie and will expire when the browser is closed.
path Used to set a web URL in the cookie. If set, the cookie will be accessible only from
that URL. To make a cookie accessible through a domain, set '/' as cookie path.
domain The domain of your web application. It can be used to limit access of cookie for sub-
domains.
secure If you set this to 1, then the cookie will be available and sent only over HTTPS
connection.
So if we want to create a cookie to store the name of the user who visited your website, and set an expiration
time of a week, then we can do it like this,
<?php
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
To access a stored cookie we use the $_COOKIE global variable, and can use the isset() method to check
whether the cookie is set or not.
Example :
<?php
// set the cookie
setcookie ("username", "iamabhishek", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body> 8
</html>
So by providing the name of the cookie inside the square brackets with the global variable $_COOKIE[ ] we can
access the cookie.
NOTE: setcookie() function should be placed before the starting HTML tag(<html>).
<?php
// updating the cookie
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
}
else
?>
</body>
</html>
<?php
// updating the cookie
?>
<html>
<body>
<?php
echo "cookie username is deleted!";
?>
</body>
</html>
1. Web applications which require a user to login, use session to store user information, so that on every
webpage related information can be displayed to the user.
2. In eCommerce web stores, shopping cart is generally saved as part of session.
10
<?php
// start the session
session_start();
$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>
<html>
<body>
<?php
echo "Session variable is set.";
?>
<a href="second_page.php">Go to Second Page</a>
</body>
</html>
NOTE: The function session_start() should be the first statement of the page, before any HTML tag.
<?php
// start the session 11
session_start();
$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
?>
</body>
</html>
Output :
Username is: iamabhishek
User id is: 1
session_start () function is used to initialize a new session and to fetch the ongoing session(if already started),
and then, using the $_SESSION global variable, we can either set new values into the session or get the saved
values.
If there are too many values stored in the session, and you don't know which one do you want to get, you can
use the below code to print all the current session variable data.
Example :
<?php
// start the session
session_start();
?>
<html>
<body>
<?php
12
print_r ($_SESSION);
?>
</body>
</html>
Output :
Array (
[userid] => 1
<?php
// start the session
session_start ();
?>
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
?>
</body>
</html>
13
<?php
// start the session
session_start ();
?>
<html>
<body>
<?php
// clean the session variable
session_unset ();
session_destroy ();
?>
</body>
</html>
Set A
1. Write a PHP script to keep track of number of times the web page has been access.
[Use session and cookies]
2. Write a PHP script to change the preferences of your web page like font style, font size, font color,
background color using cookie. Display selected setting on next web page and actual implementation
(with new settings) on third page.
Set B
1. Write a PHP script to accept username and password. If in the first three chances, username and
password entered is correct then display second form with “Welcome message” otherwise display error
message. [Use Session]
2. Write a PHP script to accept Employee details (Eno, Ename, Address) on first page. On second page
accept earning (Basic, DA, HRA). On third page print Employee information (Eno, Ename, Address,
Basic, DA, HRA, Total) [ Use Session]
14
Set C
1. Crete a form to accept customer information ( Name, Addr, MobNo). Once the customer
information is accepted, accept product information in the next form (ProdName, Qty,Rate).
Generate the bill for the customer in the next form. Bill should contain the customer information and the
information of the products entered.
15
Syntax:
university.css :
uname
{
color:black;
font-family:copperplate Gothoic Light;
font-size:16 pt;
font:bold;
}
city
{
color:yellow;
font-family:Arial;
font-size:12 pt;
font:bold;
}
rank
{
color:yellow;
font-family:Arial;
font-size:16 pt;
font:bold;
}
university.xml :
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="university.css"?>
<university>
<univ>
<uname>Pune University</uname>
<city>Pune</city>
<rank>2</rank>
</univ>
<univ>
<uname>Kolhapur University</uname>
<city>Kolhapur</city>
<rank>4</rank>
</univ>
</university> 16
What is DOM?
The W3C DOM provides a standard set of objects for HTML and XML documents, and a standard interface for
accessing and manipulating them.
The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM Level
1/2/3):
Core DOM - defines a standard set of objects for any structured document
XML DOM - defines a standard set of objects for XML documents
HTML DOM - defines a standard set of objects for HTML documents
XML Parsing
To read and update - create and manipulate - an XML document, you will need an XML parser.
Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole
document, and provides access to the tree elements
17
Event-based parser : Views an XML document as a series of events. When a specific event occurs, it
calls a function to handle it.
We want to initialize the XML parser, load the xml, and output it:
DomDocument Example :
Create XML File “ Book.xml “
<BookInfo>
<book>
<bookno>1</bookno>
<bookname>JAVA</bookname>
<price>250</price>
<year>2006</year>
</book>
<book>
<bookno>2</bookno>
<bookname>PHP</bookname>
<authorname> S.Kadam</authorname>
<price>350</price>
<year>2009</year>
</book>
<book>
<bookno>3</bookno>
<bookname>C</bookname>
18
<price>500</price>
<year>1971</year>
</book>
<book>
<bookno>4</bookno>
<bookname>C++</bookname>
<price>400</price>
<year>1994</year>
<book>
<bookno>5</bookno>
<bookname>DATABASE</bookname>
<price>700</price>
<year>2001</year>
</book>
</BookInfo>
$dom=new DomDocument();
$dom->load("book.xml");
$bname=$dom->getElementsByTagName("bookname");
foreach($bname as $b)
echo "<b>$b->textContent<b><br><br>";
} 19
?>
What is SimpleXML?
SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML
document's layout.
Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an
element.
Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than
one element on one level, they're placed inside an array
Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name
Element Data - Text data from elements are converted to strings. If an element has more than one text
node, they will be arranged in the order they are found
SimpleXML is fast and easy to use when performing basic tasks like:
20
<empdetails>
<employee>
<empno>1</empno>
<empname>Sagar</empname>
<salary>20000</salary>
<designation>Clerk</designation>
</employee>
<employee>
<empno>2</empno>
<empname>Shubham</empname>
<salary>30000</salary>
<designation>Manager</designation>
</employee>
<employee>
<empno>3</empno>
<empname>Abhishekh</empname>
<salary>500000</salary>
<designation>CEO</designation>
</employee>
</empdetails>
21
Employee.php :
<?php
$xml=simplexml_load_file("Employee.xml");
foreach($xml->employee as $emp)
?>
Set A :
3) Write a PHP script to generate an XML file in the following format in PHP.
<?xml version="1.0" encoding="UTF-8"?>
<BookInfo>
<book>
<bookno>1</bookno>
<bookname>JAVA</bookname>
<authorname> Balguru Swami</authorname>
<price>250</price>
<year>2006</year>
</book>
<book>
<bookno>2</bookno>
22
<bookname>C</bookname>
<authorname> Denis Ritchie</authorname>
<price>500</price>
<year>1971</year>
</book>
</BookInfo>
Set B
1. Write PHP script to read above created “book.xml” file into simpleXML object. Display attributes and elements
.(Hint L simple_xml_load_file() function )
2. Write a PHP script to read “Movie.xml” file and print all MovieTitle and ActorName of file using DOMDocument
Parser. “Movie.xml” file should contain following information with at least 5 records with values.
MovieInfo
MovieNo, MovieTitle, ActorName , ReleaseYear
Set C
1. Create a XML file which gives details of movies available in “Movie CD Store “ from following categories
a) Classical
b) Horror
c) Action
Elements in each category are in the following format
<Category>
<MovieTitle> ……………. </ MovieTitle >
<ActorName> ……………….</ActorName>
<ReleaseYear> ………………… </ReleaseYear>
</Category>
Save the file with name “movies.xml”
23
Javascript is basically designed to create interactivity with HTML pages. It enables you to read and change the
content of HTML controls and also enables you to load a specific page depending upon the client’s request. It
helps you to do certain validations on client side.
Variables: Value of a variable can change during the script. No need to declare a variable.
Conditional statements and loops: In Javascript , the syntax of Conditional statements and loops are same as
that of PHP, C programming.
Javascript Object
Objects in Javascript are divided into three categories.
1. Built-in objects
2. Browser Objects
3. User-defined objects.
Built-in Objects:
Array, string, math, Date are commonly used built-in objects.
Array: Using Keyword new, you can create an instance of the object.
For ex. Varmyarray=new Aarray();
String: String object is used to manipulate a stored piece of text.
Var text =”PHP and Javascript”
Document.write(text.length);
Math: This object is used to perform common mathematical tasks .
Javascript provides eight mathematical values that can be accessed from the
math object.
These are
Math.E
Math.PI
Math.SQRT2
Math.SQRT 1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Ex. Round method is used to round a number
Document.write(Math.round(4.7))
Date: This object works with date and time
VarmyDate=new Date()
myDate.setFullYear(2015, 0, 20)
Browser Objects :
BOM is a collection of objects that interact with the browser window. These objects include the Window object,
history object, location object, navigator object, screen object and document object.The window object
method is the top object in BOM hierarchy. The window24 object is used to move, resize windows , create a new
windows. Window object is also used to create dialogue boxes such as alert boxes. Some commonly used methods
of window object are open, close, confirm, alert, prompt etc.
2) getElementByTagName() method:
This method returns all elements with the specified tag name.
Refer the examples given below.
1) simplejavascript example
<!DOCTYPE html>
<html>
<body>
<script type=”text/javascript”>
Document.write(“Hello World!”)
</script>
</body>
</html>
2) javascript example using 'alert box ' window object.
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
3)javascript example using 'document.write method'.
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
Popup boxes :JavaScript has three kind of popup boxes: Alert box, Confirm
box, and Prompt box.
Alert Box: An alert box is often used if you want to make sure information
comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
25
Syntax
window.alert("sometext");
The window.alert() method can be written without the window prefix.
Example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display an alert box:</p>
<button onclick="myFunction()">Try it</button>
<script>
functionmyFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
Confirm Box :A confirm box is often used if you want the user to verify or accept something. When a confirm
box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box
returns true. If the user clicks "Cancel", the box returns false.
Syntax
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
Example
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
Prompt Box :A prompt box is often used if you want the user to input a value before entering a page. When a
prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the
user clicks "Cancel" the box returns null.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
Example
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
HTML Events
An HTML event can be something the browser does, or something a user
does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
26
This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object
in one statement.
An object literal is a list of name: value pairs (like age:50) inside curly braces {}.
The following example creates a new JavaScript object with four properties:
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
27
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
functionfunctionName(parameters) {
28
code to be executed
}
Declared functions are not executed immediately. They are "saved for later use", and will be executed later,
when they are invoked (called upon).
Example
<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which performs a calculation,
and returns the result:</p>
<p id="demo"></p>
<script>
functionmyFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML =
myFunction(4, 3);
</script>
</body>
</html>
jQuery
What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier
to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code
to accomplish, and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that
the <script> tag should be inside the <head> section):
<head>
<script src="jquery-3.5.1.min.js"></script>
</head>
29
jQuery CDN
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery
Network).Google is an example of someone who host jQuery:
Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
But this will execute only when you are online. So if you have to run your scripts offline you have to use the
library option, ie
<head>
<script src="jquery-3.5.1.min.js"></script>
</head>
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).
Examples:
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or
select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more.
It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
30
Example
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.5.1.min.js">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
</body>
</html>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Syntax Description
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to
"_blank"
32
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT
equal to "_blank"
$("*")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("*").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body> </html>
$(this)
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
33
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
$("p.intro")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p.intro").hide();
});
});
</script>
</head>
<body>
<button>Click me</button>
</body>
</html>
$("p:first")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p:first").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p> 34
<button>Click me</button>
</body>
</html>
$("ulli:first")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("ulli:first").hide();
});
});
</script>
</head>
<body>
<p>List 1:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>
<p>List 2:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>
<button>Click me</button>
</body>
</html>
$("ulli:first-child")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("ulli:first-child").hide();
});
});
</script> 35
</head>
<body>
<p>List 1:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>
<p>List 2:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>
<button>Click me</button>
</body>
</html>
$("[href]")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("[href]").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><a href="https://www.w3schools.com/html/">HTML Tutorial</a></p>
<p><a href="https://www.w3schools.com/css/">CSS Tutorial</a></p>
<button>Click me</button>
</body>
</html>
36
$("a[target='_blank']")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("a[target='_blank']").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><a href="https://www.w3schools.com/html/" target="_blank">HTML Tutorial</a></p>
<p><a href="https://www.w3schools.com/css/">CSS Tutorial</a></p>
<button>Click me</button>
</body>
</html>
$("a[target!='_blank']")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("a[target!='_blank']").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><a href="https://www.w3schools.com/html/" target="_blank">HTML Tutorial</a></p>
<p><a href="https://www.w3schools.com/css/">CSS Tutorial</a></p>
<button>Click me</button>
</body></html> 37
$(":button")
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(":button").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
$("tr:even")
$("tr:odd")
38
});
</script>
<style>
div{
border: 1px solid;
background-color:red;
margin: 2px 0 2px 0;
}
</style>
</head>
<body>
<h1>Demo: jQueryafter() method </h1>
<div id="div1">div 1
</div>
<div id="div2">div 2
</div>
</body>
</html>
jQuery before() Method
The jQuerybefore() method inserts content (new or existing DOM elements) before target element(s) which is
specified by a selector.
Syntax:
$('selector expression').before('content');
Specify a selector to get the reference of target element(s) before which you want to add the content and then
call before() method. Pass the content string that can be any valid HTML element as parameter.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.5.1.min.js"></script>
<script>
39
$(document).ready(function () {
});
</script>
<style>
div{
border: 1px solid;
background-color:red;
margin: 2px 0 2px 0;
}
</style>
</head>
<body>
<h1>Demo: jQuerybefore() method </h1>
<div id="div1">div 1
</div>
jQuery append() Method
The jQueryappend() method inserts content to the end of target element(s) which is specified by a selector.
Syntax:
$('selector expression').append('content');
First specify a selector expression to get the reference of an element(s) to which you want to append content,
then call append() method and pass content string as a parameter.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function () {
$('p').append('World!');
});
</script>
</head>
<body>
<h1>Demo: jQueryappend() method </h1>
<p>Hello </p>
</body>
</html>
<script src="jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function () {
});
</script>
</head>
<body>
<h1>Demo: jQueryprepend() method </h1>
<div>
<label>This is div.</label>
</div>
</body>
</html>
$('label').remove();
});
</script>
</head>
<body>
<h1>Demo: jQueryremove() method </h1>
<div>This is div.
<label>This is label.</label>
</div>
</body>
</html>
jQueryreplaceAll() Method
The jQueryreplaceAll() method replaces all target elements with specified element(s).
Syntax:
$('content string').replaceAll('selector expression');
Here, syntax is different. First specify a content string as replacement element(s) and then call replaceAll()
method with selector expression to specify a target element(s).
<!DOCTYPE html>
41
<html>
<head>
<script src="jquery-3.5.1.min.js"></script> <script>
$(document).ready(function () {
$('<span>This is span</span>').replaceAll('p');
});
</script>
</head>
<body>
<h1>Demo: jQueryreplaceAll() method </h1>
<div>
<p>This is paragraph.</p>
</div>
<p>This is another paragraph.</p>
</body>
</html>
jQuery wrap() Method
The jQuerywrap() method wrap each target element with specified content element.
Syntax:
$('selector expression').wrap('content string');
Specify a selector to get target elements and then call wrap method and pass content string to wrap the target
element(s).
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function () {
$('span').wrap('<p></p>');
});
</script>
</head>
<body>
<h1>Demo: jQuerywrap() method </h1>
<div>
<span>This is span.</span>
</div>
<span>This is span.</span>
</body>
</html>
42
Example of appending in paragraph text and in unordered list in a given HTML document using jQuery
selectors.
<!DOCTYPE html>
<html>
<head>
<script src=“jquery-3.5.1.min.js”></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
$("#btn2").click(function(){
$("ul").append("<li>Appended item</li>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
</body>
</html>
$("#btn2").click(function(){
$("p").after("<i>After</i>");
});
});
</script>
</head>
<body>
</body>
</html>
SET A:
1) Write a javascript to display message ‘Exams are near, have you started preparing for?’ using alert,
prompt and confirm boxes. Accept proper input from user and display messages accordingly.
2) Add or append in paragraph text and also in the numbered(ordered) list in a given HTML document
using jQuery selectors.
[Hint : Use Append( ) method]
SET B:
1) Write a javascript function to validate username and password for a membership form.
2) To insert text before and after an image using jQuery.
[Hint : Use before( ) and after( )]
SET C:
1) Write a Javascript program to accept name of student, change font color to red, font size to 18 if student
name is present otherwise on clicking on empty text box display image which changes its size (Use
onblur, onload, onmousehover, onmouseclick, onmouseup)
2) Remove div section elements after clicking on button using jQuery.
[Hint : Use #id selector]
Assignment Evaluation
44
AJAX is not a new programming language, but a new way to use existing standards.
AJAX is the art of exchanging data with a server, and updating parts of a web page - without
reloading the whole page.
XMLHttpRequest is a JavaScript object capable of calling the server and capturing its
response. It is used to send HTTP or HTTPS requests to a web server and load the server
response data back into the script.
All modern browsers (IE, Firefox, Chrome, Safari, and Opera) have a built- in XMLHttpRequest
object.
xmlhttp=new XMLHttpRequest();
When a request to a server is sent, we want to perform some actions based on the
response.
The onreadystatechange event is triggered every time the readyState
changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:
Property Description
onreadystatechange
Stores a function (or the name of a function) to be
called automatically each time the readyState property
changes
readyState Holds the status of the XMLHttpRequest.
Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
Status 200: "OK"
404: Page not found
In the onreadystatechange event, we specify what will happen when the server response is
ready to be processed. 45
The onreadystatechange event is triggered five times (0-4), one time for each change in
readyState.
To get the response from a server, use the responseText or responseXML property of the
XMLHttpRequest object. The responseText property returns the response as a string.
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
Method Description
open(method,url,async)
Specifies the type of request, the URL, and if the
request should be handled asynchronously or not.
Example 1:
Write a Ajax program to search Student Name according to the character typed and display list using
array.
<?php
$n=$_GET['n'];
$a=array();
$a[]="sonal";
$a[]="sanjay";
$a[]="anant";
$a[]=”anushka”
$a[]=”kajal”
foreach($a as $v)
{
46
$s=substr($v,0,strlen($n));
if($s===$n)
echo "$v<br>";
?>
<html> <body>
<script type="text/javascript">
function display()
var n= document.getElementById('n').value;
x.send( );
x.onreadystatechange = function()
document.getElementById("show").innerHTML = x.responseText;
</script>
</body>
</html>
Output :
Example 2:
Write AJAX program to print movie details by selecting an Actor’s name. Create tables Movie and Actor
with 1:M cardinality as follows:
Actor (ano,aname)
[Use PostgreSQL]
Solution :
<html>
<body>
<script type="text/javascript">
function display()
var n= document.getElementById('n').value;
x.send( );
x.onreadystatechange = function()
document.getElementById("show").innerHTML = x.responseText;
</script>
</body>
</html>
<?php
$aname=$_POST['aname'];
if($rs!=null)
echo"<table border=0>";
while($row=pg_fetch_row($rs))
echo"<tr>";
echo"<td>".$row[0]."</td>";
echo"<td>".$row[1]."</td>";
echo"</tr>";
echo"</table>";
else
pg_close($con);
?>Output :
Run majax.php file on browser enter actor name in text box and see output
49
Set A
1. Write AJAX program to read contact.dat file and print the contents of the file in a tabular
format when the user clicks on print button. Contact.dat file should contain srno, name,
residence number, mobile number, Address. [Enter at least 3 record in contact.dat file]
2. Write AJAX program where the user is requested to write his or her name in a text box,
and the server keeps sending back responses while the user is typing. If the user name is
not entered then the message displayed will be, “Stranger, please tell me your name!”. If
the name is Rohit, Virat, Dhoni, Ashwin or Harbhajan , the server responds with “Hello,
master <user name>!”. If the name is anything else, the message will be “<user name>, I
don’t know you!”.
Set B
Set C
1. Write Ajax program to fetch suggestions when is user is typing in a textbox. (eg like
google suggestions. Hint create array of suggestions and matching string will be displayed)
2. Write Ajax program to get book details from XML file when user select a book name.
Create XML file for storing details of book(title, author, year, price).
Assignment Evaluation
(Designed by: Ms. Sarita Byagar, Indira College of Commerce and Science, Pune)
50
CodeIgniter is a powerful PHP framework with a very small footprint, built for developers
who need a simple and elegant toolkit to create full-featured web applications.
The Model represents your data structures. Typically, your model classes will contain
functions that help you retrieve, insert and update information in your database.
The View is information that is being presented to a user. A View will normally be a
web page, but in CodeIgniter, a view can also be a page fragment like a header or
footer. It can also be an RSS page, or any other type of “page”.
The Controller serves as an intermediary between the Model, the View, and any other
resources needed to process the HTTP request and generate a web page.
CodeIgniter requires PHP version 5.4 or newer and MySQL 5.1 or newer with mysqli and
pdo drivers so make sure that your system meets CodeIgniter system requirements.
1. Download codeigniter
The next thing you need to do is to navigate to your server’s directory root and
download the current version of CodeIgniter.
cd /var/www/wget
https://github.com/bcit-ci/CodeIgniter/archive/3.0.1.zip
unzip 3.0.1.zip
51
mv /var/www/CodeIgniter-3.0.1 /var/www/codeigniter
nano /etc/apache2/sites-enabled/000-default
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot /var/www/codeigniter/
ServerName yourdomain.com
ServerAlias www.yourdomain.com
<Directory /var/www/codeigniter/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/httpd/yourdomain.com-error_log
CustomLog /var/log/httpd/yourdomain.com-access_log common
</VirtualHost>
52
Once you create the MySQL database you need to change the database connectivity senttigs
to the settings needed to access your newly created database.
nano /var/www/codeigniter/application/config/database.php
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
);
Here, you need to enter your database connectivity settings. Save the file and close it.
nano /var/www/codeigniter/application/config/config.php
$config['base_url'] = 'http://yourdomain.com';
Once you enter your domain name, save the file and close it.
http://www.codeigniter.com/user_guide/
53
Set A
1. Create a CSS file to apply the following styling for an HTML document.
Background color: blue,
H1
Color : red,
Font-family : Verdana,
Font-size : 8
Color : green,
Font-family : Monospace,
Font-size :10
2. Add a Javascript file in codeigniter. The javascript code should check whether a
number is positive or negative.
Set B
1. Create a table student having attributes (rollno, name, class). Assume appropriate
data types for the attributes. Using Codeigniter , connect to the database and
insert minimum 5 records in it.
2. For the above table student, display all its records using Codeigniter.
Set C
1. Create a form to accept personal details of customer (name, age, address). Once
the personal information is accepted, on the next page accept order details such as
(product name, quantity). Display the personal details and order details on the
third page. (Use cookies) 54
2. Write a PHP script to accept Employee details ( Eno, Ename, address) on first
page. On second page accept earning (Basic, Da, HRA). On third page print
Employee information( ENO,Ename, Address, BASIC, DA, HRA, TOTAL) (Use
Session)
Assignment Evaluation
(Designed by: Ms. Sarita Byagar, Indira College of Commerce and Science, Pune)
55