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

XML, Ajax and PHP

Uploaded by

Yashasvi rana
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

XML, Ajax and PHP

Uploaded by

Yashasvi rana
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 40

Xml

It stands for eXtensible Markup Language.


XML is designed to store and transport data.
Xml was released in late 90’s and it was created to provide an easy to use and store self describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is tag base syntax language. One of the great thing about XML is that we can create our own tags and give the meaning.
XML is platform independent and language independent.
It is the foundation of several next generation web related technologies like AJAX.

Why we need to use Xml


The main benefit of xml is that you can use it to take data from a program like Microsoft SQL, convert it into XML then share that XML with
other programs and platforms.

You can communicate between two platforms which are generally very difficult.

The main thing which makes XML truly powerful is its international acceptance.
Many corporation use XML interfaces for databases, programming, office application mobile phones and more. It is due to its platform
independent feature.

How Can XML be Used?

XML is used in many aspects of web development.

XML is often used to separate data from presentation.

XML does not carry any information about how to be displayed.

The same XML data can be used in many different presentation scenarios.

Because of this, with XML, there is a full separation between data and presentation.

Advantages of XML

XML is Reusable.

Information can be read and understand easily.

XML is an open format that can be processed by any XML aware application like a browser, word processor, etc.

XML is compatible with all kinds of languages that used over internet like JSP, ASP, etc.
Disadvantages of XML
Sometime XML is not so good at handling large amount o data.

XML can quickly become difficulty when lot of information is included in one file.

Features of XML

XML is widely used in the era of web development. It is also used to simplify data storage and data sharing.
The main features of XML are given below.

1) XML separates data from HTML

2) XML simplifies data sharing

3) XML simplifies data transport

4) XML simplifies Platform change

5) XML increases data availability

6) XML can be used to create new internet languages


The Difference Between XML and HTML

XML and HTML were designed with different goals:

XML was designed to carry data - with focus on what data is.
HTML was designed to display data - with focus on how data looks.
XML tags are not predefined like HTML tags are. This means XML Does not use Predefined tags.

Tags in the XML are custom tags that can be invented by the author of the XML document.

HTML works with predefined tags like <p>, <h1>, <table>, etc.

With XML, the author must define both the tags and the document structure.

XML Separates Data from HTML?

When displaying data in HTML, you should not have to edit the HTML file when the data changes.

With XML, the data can be stored in separate XML files.

With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.
Rules for well formed XML
The first line is the XML declaration. It defines the XML version (1.0)
and the encoding used (ISO-8859-1 = Latin-1/West European
It must begin with the XML declaration i.e. XML Prolog.
o
character set).
It must have one unique root element.
o

All start tags of XML documents must match end tags.


o The next line describes the root element of the document (like saying:
"this document is a course"):
XML tags are case sensitive.
o

All elements must be closed.


o
<course>
All elements must be properly nested.
o
The next 4 lines describe 4 child elements of the root (name, sec, sem,
All attributes values must be quoted.
o
and remark).
XML entities must be used for special characters.
o
<name>BCA</name>
<sec>B</sec>
<sem>V</sem>
<remark>BCA is a three year program!</remark>
Example
And finally the last line defines the end of the root element.
<?xml version="1.0" encoding="ISO-8859-1"?>
<course> </course>
<name>BCA</name>
<sec>B</sec>
<sem>V</sem>
<remark>BCA is a three year program!</remark>
</course>
XML Attributes Example of XML
XML elements can have attributes. By the use of attributes, we can add
the information about the element. <?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
XML attributes enhance the properties of the elements. <book category="programming">
<title>JAVA</title>
Attributes are designed to contain data related to a specific element. <author> XYZ</author>
<year>2005</year>
<price>300</price>
Example 1: </book>
<book category="mobile">
<book category="programming"> </book> <title>Android</title>
<author>ABC</author>
Example 2: <year>2005</year>
<book> <price>500</price>
< category > PROGRAMMING </ category > </book>
</book> <book category="WEB">
<title>XML</title>
In the first example category is used as an attribute and in the second <author>ABC</author>
example category is an element. <year>2003</year>
<price>250</price>
Both examples provide the same information but it is good practice to </book>
avoid attribute in XML and use elements instead of attributes. </bookstore>
Tree Structure
An XML document has a self descriptive structure.

It forms a tree structure which is referred as an XML tree.

The tree structure makes easy to describe an XML document.

XML documents are formed as element trees.

An XML tree starts at a root element and branches from the root to child elements.

DOM parser represents the XML document in Tree structure.

All elements can have sub elements (child elements):

<root>
<child>
<subchild>.....</subchild>
</child>
</root>
Example of an XML document

<?xml version = "1.0"?>

<Company>
<Employee>

<FirstName >Harendra</FirstName>
<LastName>Negi</LastName>
<ContactNo>9876543210</ContactNo>
<Email>[email protected]</Email>
<Address>

<City>Dehradun</City>
<State>Uttarakhand</State>
<Zip>243001</Zip>

</Address>

</Employee>

</Company>
Tree Rules

These rules are used to figure out the relationship of the elements.

It shows if an element is a child or a parent of the other element.

Descendants: If element A is contained by element B, then A is known as descendant of B.

In the previous example “Company" is the root element and all the other elements are the descendants of "Company".

Ancestors: The containing element which contains other elements is called "Ancestor" of other element.

In the previous example root element (Company) is ancestor of all other elements.
Q1. Construct XML Tree. Q2. Write XML code which needs to follow the given structure.

<Employee>
<Name>
<First name>Brian</First name>
<Last name>Lara<</Last name>
</Name>
<Contact>
<Mobile>9800000000</Mobile>
<Landline>020222222</Landline>
</Contact>
<Address> Q3. Write XML code which needs to follow the given structure.
<City>Pune</city>
<Street>Tilak road</Street>
<Zip code>4110</Zip code>
</Address>
</Employee>
DOM
The Document Object Model (DOM) is the foundation of XML.

XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between
them.

A DOM document is a collection of nodes or pieces of information organized in a hierarchy.

This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of
information, the DOM is said to be tree based.

The HTML DOM defines a standard way for accessing and manipulating HTML documents. It presents an HTML document as a tree-
structure.

The XML DOM defines a standard way for accessing and manipulating XML documents. It presents an XML document as a tree-structure.

Understanding the DOM is a must for anyone working with HTML or XML.
The XML DOM is a standard for how to get, change, add, and delete XML elements.
Example of an XML document

<?xml version = "1.0"?>

<Company>
<Employee>

<FirstName>Harendra</FirstName>
<LastName>Negi</LastName>
<ContactNo>9876543210</ContactNo>
<Email>[email protected]</Email>
<Address>

<City>Dehradun</City>
<State>Uttarakhand</State>
<Zip>243001</Zip>

</Address>

</Employee>

</Company>
What is DTD

DTD stands for Document Type Definition.

It defines the legal building blocks of an XML document.

It is used to define document structure with a list of legal elements and attributes.

Its main purpose is to define the structure of an XML document.

It contains a list of legal elements and define the structure with the help of them.

With a DTD, you can verify that the data you receive from the outside world is valid.

You can also use a DTD to verify your own data.

When you are working with small XML files, creating DTDs may be a waste of time.

Use of DTD is to validate the XML document.

There are two types of DTD.

•Internal DTD
•External DTD
Internal DTD
A DTD is referred as an internal DTD if elements are declared within the XML files.
To refer it as an internal DTD, standalone attribute in xml declaration must be set to yes.
This means, the declaration works independent of external source.

Syntax:

<!DOCTYPE root-element [element-declaration]>

Where root-element is the name of root element and element declaration is where you want to declare the elements.
Eg:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE address[
<!ELEMENT addresss (name,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>

<address>
<name>Harendra</name>
<phone>1234567</phone>
</address>
<!DOCTYPE address: defines root element of document.

<!ELEMENT address: defines that address must contain name, and phone.

<!ELEMENT name: defines that name is the type of #PCDATA.

<!ELEMENT phone: defines that phone is the type of #PCDATA.

#PCDATA: is a parse-able text data or parse character data. It is String data type.

It means characters are to be parsed by XML. XML parsers are used to parse all text in an XML document.

1.DOM

2.SAX (Simple API for XML)


External DTD
In external DTD, elements are declared outside the XML file.

To refer it as external DTD, standalone attribute in the XML declaration must be set as no.

This means, declaration includes information from the external source.

Syntax:

<!DOCTYPE root-element SYSTEM “file-name”>

Where file-name is the file with .dtd extension.

SYSTEM is an identifier which enables you to specify the location of an external file containing DTD declarations.
XML CODE DTD CODE: employee.DTD

<?xml version="1.0" encoding="UTF-8" standalone="no"? <!ELEMENT addresss (name,phone)>


> <!ELEMENT name1 (#PCDATA)>
<!DOCTYPE address SYSTEM "employee.dtd"> <!ELEMENT phone1 (#PCDATA)>
<address> ]>
<name>Harendra</name>
<phone>1234567</phone>
</address>
AJAX
AJAX stands for Asynchronous JavaScript and XML. It is a group of inter-related technologies like JavaScript, XML, HTML
etc.

AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.

AJAX allows you to send only important information to the server not the entire page. So only valuable data from the client
side is routed to the server side. It makes your application interactive and faster.

AJAX is not a programming language. AJAX just uses a combination of:

A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means
that it is possible to update parts of a web page, without reloading the whole page.
How AJAX Works

1. An event occurs in a web page (the page is loaded, a button


is clicked)

2. An XMLHttpRequest object is created by JavaScript

3. The XMLHttpRequest object sends a request to a web server

4. The server processes the request

5. The server sends a response back to the web page

6. The response is read by JavaScript

7. Proper action (like page update) is performed by JavaScript


Synchronous vs Asynchronous
Synchronous Asynchronous

A synchronous request blocks the An asynchronous request doesn’t block the client i.e.
client until operation completes i.e. browser is responsive.
browser is unresponsive.
At that time, user can perform another operations
In such case, JavaScript engine of the also. In such case, JavaScript engine of the browser is
browser is blocked. not blocked.

It is a classic web Application Model It is a AJAX web Application Model


AJAX - The XMLHttpRequest Object

An object of XMLHttpRequest is used for asynchronous communication between client and server.

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to
update parts of a web page, without reloading the whole page.

It performs following operations:

1.Sends data from the client in the background


2.Receives the data from the server
3.Updates the webpage without reloading it.

The common properties of XMLHttpRequest object are as follows:


Property Description

It is called whenever readystate attribute changes. It must not


onReadyStateChange
be used with synchronous requests.

represents the state of the request. It ranges from 0 to 4. 0


UNOPENED open() is not called.
1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and headers and
readyState
status are available.
3 LOADING Downloading data; responseText holds the
data.
4 DONE The operation is completed fully.

reponseText returns response as text.


responseXML returns response as XML
Methods of XMLHttpRequest object
The important methods of XMLHttpRequest object are as follows:

Method Description

void open(method, URL) opens the request specifying get or post method and url.

void open(method, URL, async) same as above but specifies asynchronous or not.

void open(method, URL, async, username, password) same as above but specifies username and password.

void send() sends get request.

void send(string) send post request.

setRequestHeader(header,value) it adds request headers.


What is PHP?
PHP stands for Hypertext Preprocessor.
PHP is a server-side scripting language, like ASP.
PHP scripts are executed on the server.
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.).
PHP is an open source software.
PHP is free to download and use.
PHP files can contain text, HTML tags and scripts.
PHP files are returned to the browser as plain HTML.
PHP files have a file extension of ".php", ".php3", or ".phtml".
History of PHP

PHP was originally created by a developer named Rasmus Lerdorf.


PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL
database.

•It handles dynamic content, database as well as session tracking for the website.

•You can create sessions in PHP.

•It can access cookies variable and also set cookies.

•It helps to encrypt the data and apply validation.

•As PHP is easy to install and set up, this is the main reason why PHP is the best language to learn.

•PHP can handle the forms, such as - collect the data from users using forms, save it into the database, and
return useful information to the user. For example - Registration form.

•PHP is very popular language because of its simplicity and open source.
PHP Installation
Most people would prefer to install a all-in-one solution.
The PHP Community Provides Some types of Software Server solution under The GNU (General Public
License).
These are the following:
1.WAMP Server
2.LAMP Server
3.MAMP Server
4.XAMPP Server
All these types of software automatically configure inside operating system.

After installation, it having PHP, MySQL, Apache and operating system base configuration file, it doesn't need to
configure manually.

WAMP Microsoft window o/s, Apache Mysql PHP


LAMP Linux Operating System Apache Mysql PHP
MAMP Mac os Apache Mysql PHP
XAMPP x-os(cross operating system) Apache Mysql PHP Perl
Syntax Example:
<?php <?php
echo "Welcome Students";
?> ?>

Comments in PHP 2. Multi-lines comments


There are two types of comments used in php. Multi lines comments used to comment multiple lines.

1. Single line comments Here we can give comments in bulk.


Single line comment used for short explanations.
The bulk comments are enclose within (/*.....*/)
Declaration of Single line comment are two types.
<?php
Either Begin with (#) or backslash(//)

<?php /*
This is Multiline Comments
# This is the next line comment */

// This is also a single line comment. ?>


?>
Variables
Variable is nothing, it is just name of the memory location.

A Variable is simply a container i.e. used to store both numeric and non-numeric information.

Variables in PHP starts with a dollar($) sign, followed by the name of the variable.

The variable name must begin with a letter or the underscore character.

A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

A variable name should not contain space

Example
<?php
$txt ="Hello World!";
$x=16;
?>
PHP is a Loosely Typed Language
In PHP, a variable does not need to be declared before adding a value to it.

In the example above, you see that you do not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.

In PHP, the variable is declared automatically when you use it.

<?php

$str="hello string";
$x=200;
$y=44.6;

echo "string is: $str <br/>";


echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
To concatenate two string variables together, use the concatenation operator denoted by (.)

<?php

$a=“Good Morning Students !!!! “ ;

$b=“What’s Going On";

echo $a . “ “ . $b;
?>

Variable names in PHP are case-sensitive Inspecting Variable Contents(Variable Property)


<?php
<?php
$a = 100;
$name=“Harendra";
$b = 200;
$NAME=“Singh";
$c = $a + $b;
echo $name. “ “ ;
var_dump ($c);
echo $NAME;

?> ?>
Output Output
Harendra Singh int 300
Variable Scope
The scope of a variable is defined as its range in the program under which it can be accessed.

In other words, "The scope of a variable is the portion of the program within which it is defined and can be accessed.“

PHP has three types of variable scopes:


1.Local variable

2.Global variable

3.Static variable

Local variable
The variables that are declared within a function are called local variables for that function.

These local variables have their scope only in that particular function in which they are declared.

This means that these variables cannot be accessed outside the function, as they have local scope.
<?php
<?php function disp()

function disp() { {
$a = "PHP";
$a = 4; //local variable
echo “Unit V is based on: " .$a;
echo "Local variable = ". $a; }
} disp();
echo $a;
disp();
//use of local variable outside the function will generate an error
?>
?>
Output:
Output:
Local variable = 4
Unit V is based on: PHP
Undefined variable: a
Global variable
The global variables are the variables that are declared outside the function.

These variables can be accessed anywhere in the program.

To access the global variable within a function, use the GLOBAL keyword before the variable.

However, these variables can be directly accessed or used outside the function without any keyword.

Therefore there is no need to use any keyword to access a global variable outside the function.
Example:
Example:
<?php
<?php
$a = "Java";
$a = "Java";
function disp() {
function disp()
global $a;
{
echo "Unit V is based on : ". $a;
echo $a;
echo "<br/>"; }
}
disp();
disp();
echo " Outside the function " . $a;
?> Output: Unit V is based on : Java
?> Output: Undefined variable
Name outside the function: Java
Use $GLOBALS instead of global
Another way to use the global variable inside the function is predefined $GLOBALS array.
If two variables, local and global, have the same name, then the local
Example:
variable has higher priority than the global variable inside the function.
<?php
Example:
$num1 = 15;
<?php
$num2 = 18;
$a = 5;
function add()
function disp()
{
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
$a = 7;

echo "Sum of global variables is: " . $sum; echo " Value of a = " . $a;
}
}
disp();
add();
?>
?>
Output: Output:

Sum of global variables is: 33 Value of a= 7


Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.

Sometimes we need to store a variable even after completion of function execution.

Therefore, another important feature of variable scoping is static variable.

We use the static keyword before the variable to define a variable, and this variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program execution leaves the scope.

<?php
function disp() OUTPUT:
{ Static: 2
static $num1 = 1; Non-static: 4
Static: 3
$num2 = 3; Non-static: 4
$num1++;
$num2++; You have to notice that $num1 regularly increments after each function
echo "Static: " .$num1 ."</br>"; call, whereas $num2 does not. This is why because $num1 is not a static
echo "Non-static: " .$num2 ."</br>"; variable, so it freed its memory after the execution of each function call.
}
disp();
disp();
?>
Form
Form is used to take input from users.

In PHP if you want to take input from keyboard and display the output according to input, in this case you have to use html form.

To get form data, we need to use PHP superglobals $_GET and $_POST.

The form request may be get or post.

To retrieve data from get request, we need to use $_GET, for post request $_POST.

Get Form
Get request is the default form request.
The data passed through get request is visible on the URL browser so it is not secured.
You can send limited amount of data through get request.

Post Form
Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured.
You can send large amount of data through post request.
Example: Get Request Example: Post Request
File: index.html File: index2.html
<form action="p11home.php">
<form action="login.php" method="post">
Name <input type="text" name="name"> Name:<input type="text" name="name"/>

<input type="submit" value="click"> Password: <input type="password" name="password"/>


<input type="submit" value="login"/>
</form>
</form>

File: login.php
File: p11home.php <?php
<?php
$name1=$_GET["name"]; $name=$_POST["name"];
$password=$_POST["password"];
echo"Welcome, $name1";
echo "Welcome: $name, your password is: $password";
?> ?>
PHP isset()
isset() function is used to check if a variable exists in the code or not.

It means we check the value of any particular variable.

We use the isset function to check if any variable that is passed, exists in the code and also possess some value.

If a variable have some value then it is said to be set and if it doesn't have any value stored in it that is contains NULL then it is said to be unset.

It returns the result as Boolean.

If we pass any variable in the isset function, it returns the result as either True or False.

If the variable that we have passed has been declared and also contain some value other than NULL then it will be returning True as the result
but if the variable is not declared or defined in the code that means either there is no such variable present in the code or it has a NULL value
then it will return False as the result.

We can check multiple variables at a time by passing multiple variables in the Isset().

In this case, function will check each and every variable whether it is set or unset and if all the variables are set then it will return True and if
any of the variable is unset then it will return False.

Syntax:- isset(variable);
<?php <?php
$a = 5; $a=5;
//variable 'a' is declared & defined $b=6;
$c=NULL;
if (isset($a)) //False because 'c' is NULL
{ //it will return true or false

echo "True"; if(isset($a, $b, $c))


//print True if isset return the True value {
echo "All the variables are set.";
} }
else
else {
{
echo "Any or All variables are Unset.";
echo "False";
}
//print False if isset return the False value
} ?>
?>
Output: Any or All variables are Unset.
Output: True
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser.

It is used to recognize the user.

Cookie is created at server side and saved to client browser.

Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at
the server side.

In short, cookie can be created, sent and received at server end.

PHP Cookie must be used before <html> tag.

PHP setcookie() function

PHP setcookie() function is used to set cookie with HTTP response.

Once cookie is set, you can access it by $_COOKIE superglobal variable.


PHP Session

PHP session is used to store and pass information from one page to another temporarily (until user close the website).

PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g.
username, product code, product name, product price etc from one page to another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers.

PHP session_start() function

PHP session_start() function is used to start the session.

It starts a new or resumes existing session.

It returns existing session if session is created already.

If session is not available, it creates and returns new session

PHP Destroying Session

PHP session_destroy() function is used to destroy all session variables completely.

You might also like