AJAX JSON PHPSession Cookie

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Ajax

12-Oct-19
AJAX – Intro..
 Ajax (sometimes capitalized as AJAX) stands for
Asynchronous JavaScript And XML
 Ajax is a technique for creating “better, faster, more
responsive web applications”
 Web applications with Ajax are supposed to replace all
our traditional desktop applications
 These changes are so sweeping that the Ajax-enabled
web is sometimes know as “Web 2.0”
 AJAX applications are Browser and Platform
Independent.
How Ajax works
 You do something with an HTML form in your browser
 JavaScript on the HTML page sends an HTTP request
to the server
 The server responds with a small amount of data, rather
than a complete web page
 JavaScript uses this data to modify the page

 This is faster because less data is transmitted and


because the browser has less work to do
Why AJAX?
Underlying technologies
 JavaScript (to display/interact with the information)
 HTML
 CSS (for styling the data)
 XML
 XML is often used for receiving data from the server
 Plain text can also be used, so XML is optional
 HTTP
 XMLHttpRequest (to exchange data asynchronously
with a server)
Starting from the browser…
 JavaScript has to handle events from the form, create
an XMLHttpRequest object, and send it (via HTTP)
to the server
 Every server can handle HTTP requests
 Despite the name, the XMLHttpRequest object does not
require XML
The XMLHttpRequest object
 JavaScript has to create an XMLHttpRequest object
 For historical reasons, there are three ways of doing this
 For most browsers, just do
var request = new XMLHttpRequest();
 For some versions of Internet Explorer, do
var request = new ActiveXObject("Microsoft.XMLHTTP");
 For other versions of Internet Explorer, do
var request = new ActiveXObject("Msxml2.XMLHTTP");
 Doing it incorrectly will cause an Exception
 The next slide shows a JavaScript function for choosing
the right way to create an XMLHttpRequest object
Getting the XMLHttpRequest object
var request = null; // we want this to be global

function getXMLHttpRequest( ) {
try { request = new XMLHttpRequest(); }
catch(err1) {
try { request = new ActiveXObject("Microsoft.XMLHTTP"); }
catch(err2) {
try { request = new ActiveXObject("Msxml2.XMLHTTP"); }
catch(err3) {
request = null;
}
}
}
if (request == null) alert("Error creating request object!");
}
Preparing the XMLHttpRequest object
 Once you have an XMLHttpRequest object, you have
to prepare it with the open method
 request.open(method, URL, asynchronous)
 The method is usually 'GET' or 'POST'

 The URL is where you are sending the data

 If using a 'GET', append the data to the URL


 If using a 'POST', add the data in a later step
 If asynchronous is true, the browser does not wait for a
response (this is what you usually want)
 request.open(method, URL)
 As above, with asynchronous defaulting to true
Sending the XMLHttpRequest object
 Once the XMLHttpRequest object has been prepared, you have
to send it
 request.send(null);
 This is the version you use with a GET request
 request.send(content);
 This is the version you use with a POST request
 The content has the same syntax as the suffix to a GET request
 POST requests are used less frequently than GET requests
 For POST, you must set the content type:
request.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
request.send('var1=' + value1 + '&var2=' + value2);
The escape method
 In the previous slide we constructed our parameter list
to the server
 request.send('var1=' + value1 + '&var2=' + value2);
 This list will be appended to the URL (for a GET)
 However, some characters are not legal in a URL
 For example, spaces should be replaced by %20
 The escape method does these replacements for you
 request.send('var1=' + escape(value1) + '&var2=' +
escape(value2));
Putting it all together
 Head:
 function getXMLHttpRequest () { ... } // from an earlier slide
 function sendRequest() {
getXMLHttpRequest();
var url = some URL
request.open("GET", url, true); // or POST
request.onreadystatechange = handleTheResponse;
request.send(null); // or send(content), if POST
 function handleTheResponse() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
// do something with the response string
} else {
alert("Error! Request status is " + request.status);
}
}
}
 Body: <input value="Click Me" type="button" onclick="sendRequest">
On the server side
 The server gets a completely standard HTTP request
 In a servlet, this would go to a doGet or doPost method
 The response is a completely standard HTTP response,
but…
 …Instead of returning a complete HTML page as a
response, the server returns an arbitrary text string
(possibly XML, possibly something else)
Getting the response
 Ajax uses asynchronous calls—you don’t wait for the response
 Instead, you have to handle an event
 request.onreadystatechange = someFunction;

 This is a function assignment, not a function call


 Hence, there are no parentheses after the function name

 When the function is called, it will be called with no parameters


 function someFunction() {
if(request.readyState == 4){
var response = request.responseText;
if (http_request.status == 200) {
// Do something with the response
}
}
}
 To be safe, set up the handler before you call the send function
The magic number 4
 The callback function you supply is called not just once, but
(usually) four times
 request.readystate tells you why it is being called
 Here are the states:
 0 -- The connection is uninitialized

 This is the state before you make the request, so your callback
function should not actually see this number
 1 -- The connection has been initialized
 2 -- The request has been sent, and the server is
(presumably) working on it
 3 -- The client is receiving the data
 4 -- The data has been received and is ready for use
The magic number 200
 A ready state of 4 tells you that you got a response--it
doesn’t tell you whether it was a good response
 The http_request.status tells you what the server
thought of your request
 404 Not found is a status we are all familiar with
 200 OK is the response we hope to get
Using response data
 When you specify the callback function,
request.onreadystatechange = someFunction;
you can’t specify arguments
 Two solutions:
 Your function can use the request object as a global variable
 This is a very bad idea if you have multiple simultaneous requests
 You can assign an anonymous function:
request.onreadystatechange = function() { someFunction(request); }
 Here the anonymous function calls your someFunction with the
request object as an argument.
Displaying the response
 http_request.onreadystatechange =
function() { showContentsAsAlert(http_request); };
http_request.open('GET', url, true);
http_request.send(null);

 function showContentsAsAlert(http_request) {
if (http_request.readyState == 4) { /* 4 means got the response */
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
The readyState property
 The readyState property defines the current state of the
XMLHttpRequest object.
 Here are the possible values for the readyState property:
 readyState=0 after you have created the XMLHttpRequest object, but
before you have called the open() method.
 readyState=1 after you have called the open() method, but before you
have called send().
 readyState=2 after you have called send().
 readyState=3 after the browser has established a communication with
the server, but before the server has completed the response.
 readyState=4 after the request has been completed, and the response
data have been completely received from the server.
 Not all browsers use all states
 Usually you are only interested in state 4
Property Description
onreadystatechange Event handler for an event that
fires at every state change

readyState Object status integer:


0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText String version of data returned
from server process

responseXML DOM-compatible document


object of data returned from
server process
status Numeric code returned by
server, such as 404 for "Not
Found" or 200 for "OK"
statusText String message accompanying
the status code
Problem: JavaScript isn’t loaded
 You put the JavaScript in an external .js file
 Some browsers ignore the external JavaScript file
 Solution: Put a space between the opening script tag
and the closing script tag
 Not this: <script type="text/javascript" src="ajax.js"></script>
 But this: <script type="text/javascript" src="ajax.js"> </script>
JSON – Javascript Object Notation
 JSON is a format for storing and transporting data.
 JSON is often used when data is sent from a server to a
web page.
 JSON is a lightweight data interchange format
 JSON is language independent *
 JSON is "self-describing" and easy to understand
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>
<p>
Name: <span id="jname"></span><br />
College: <span id="jcollege"></span><br />
Department: <span id=“jdept"></span><br />
Phone: <span id="jphone"></span><br />
</p>
<script>
var JSONObject= {
"name":“Priya",
“college":“VESIT",
“dept":computer,
"phone":“9719435021"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById(“jcollege").innerHTML=JSONObject.college
document.getElementById("jdept").innerHTML=JSONObject.dept
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>
</body>
</html>
PHP Session
What is Session Variable?
 A session is a way to store information (in variables) to
be used across multiple pages.
 Unlike a cookie, the information is not stored on the
users computer.

 Start a PHP Session


A session is started with the session_start() function.

Session variables are set with the PHP global variable:


$_SESSION.
Eg. To set Session Variable in PHP

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favclass"] = “D12A";
echo "Session variables are set.";
?>
</body>
</html> demo1.php
Eg. Display Session Variables in PHP

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favclass"] . ".";
?>
</body>
</html>

demo2.php
Eg. To Reset Session Variable in PHP

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>

Demo3.php
Eg. To Remove and Destroy Session
Variable in PHP
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>
PHP Cookies
What is a Cookie?
 A cookie is often used to identify a user.

 A cookie is a small file that the server embeds on the


user's computer. Each time the same computer requests a
page with a browser, it will send the cookie too.

 With PHP, you can both create and retrieve cookie


values.
Create Cookies with PHP
 A cookie is created with the setcookie() function.

 Syntax :

 setcookie(name, value, expire, path, domain, secure,


httponly);

 Only the name parameter is required. All other


parameters are optional.
Eg. To Create / Retrieve Cookie in PHP

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
Eg. To Delete Cookie in PHP

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>
Check if Cookies are Enabled

<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>

You might also like