0% found this document useful (0 votes)
2 views33 pages

Unit - 4

The document provides an overview of AJAX, detailing its role in creating asynchronous web applications that allow for dynamic content updates without page reloads. It covers core components such as XMLHttpRequest, JavaScript, and server-side technologies, along with methods for handling file operations, string manipulations, and regular expressions. Additionally, it includes examples of GET and POST requests, as well as a practical AJAX implementation with a database using JSP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views33 pages

Unit - 4

The document provides an overview of AJAX, detailing its role in creating asynchronous web applications that allow for dynamic content updates without page reloads. It covers core components such as XMLHttpRequest, JavaScript, and server-side technologies, along with methods for handling file operations, string manipulations, and regular expressions. Additionally, it includes examples of GET and POST requests, as well as a practical AJAX implementation with a database using JSP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit - IV

AJAX: File Handling and System Calls,


Strings and Regular Expressions, Arrays,
Cookies, Sessions, Functions, Classes,
Database Access AJAX: Asynchronous
GET/POST using XMLHttpRequest
AJAX -Asynchronous JavaScript and XML
• Ajax is a set of web development
techniques that uses various web
technologies on the client-side to create
asynchronous web applications.
• By decoupling the data interchange layer
from the presentation layer, Ajax allows
web pages and web applications, to change
content dynamically without reloading the
entire page.
• Ajax is not a technology, but rather a programming
concept. HTML and CSS can be used in
combination to mark up and style information.
• The webpage can be modified by JavaScript to
dynamically display—and allow the user to interact
with the new information.
• The built-in XMLHttpRequest object is used to
execute Ajax on webpages, allowing websites to
load content onto the screen without refreshing the
page.
• AJAX is a new technique for creating better, faster,
and more interactive web applications with the help
of XML, HTML, CSS, and Java Script.
• Ajax uses XHTML for content, CSS for presentation,
along with Document Object Model and JavaScript
for dynamic content display.
• Conventional web applications transmit information
to and from the sever using synchronous requests. It
means you fill out a form, hit submit, and get directed
to a new page with new information from the server.
• With AJAX, when you hit submit, JavaScript will make a
request to the server, interpret the results, and update the
current screen. In the purest sense, the user would never
know that anything was even transmitted to the server.

• XML is commonly used as the format for receiving server


data, although any format, including plain text, can be
used.

• AJAX is a web browser technology independent of web


server software.
• A user can continue to use the application while the
client program requests information from the server
in the background.

• Intuitive and natural user interaction. Clicking is not


required, mouse movement is a sufficient event
trigger.

• Data-driven as opposed to page-driven.


• AJAX is based on the following open
standards:
✓Browser-based presentation using HTML
and Cascading Style Sheets (CSS).
✓Data is stored in XML format and fetched
from the server.
✓Behind-the-scenes data fetches using
XMLHttpRequest objects in the browser.
✓JavaScript to make everything happen.
Core Components of AJAX
• HTML & CSS – For Presenting the contents in web application.

• Java Script – Handles client-side scripting.

• Server-side Technologies: This can include various languages like


PHP, Python, or Node.js that process requests and send back
responses, often in formats like XML or JSON.

• Document Object Model - access and update the content, structure,


and style of a document.

• XMLHttpRequest(XHR) – To send data to server asynchronously.


File Handling and System Calls
• It uses the XMLHttpRequest object to communicate with servers.
• It can send and receive information in various formats, including
JSON, XML, HTML, and text files.

• The full list of the readyState values is documented at


XMLHTTPRequest.readyState and is as follows:

•0 (uninitialized) or (request not initialized)


•1 (loading) or (server connection established)
•2 (loaded) or (request received)
•3 (interactive) or (processing request)
•4 (complete) or (request finished and response is
ready)
• The full list of the status values is documented at
XMLHTTPRequest.status and is as follows:

• 200 – OK (Server received good request).


• 400 – Bad Request.
• 404 – File not found.
• 500 – Internal Server Error.
• 505 – HTTP Version not supported.
String Method

• The search() method uses an expression to


search for a match, and returns the
position of the match.

• The replace() method returns a modified


string where the pattern is replaced.
Search
• <!DOCTYPE html>
• <html>
• <body>
• <h1>JavaScript String Methods</h1>
• <p>Search a string for “Web", and display the position of the
match:</p>
• <p id="demo"></p>
• <script>
• let text = “Lets Learn Web Programming!";
• let pos = text.indexOf(“Web”);
• document.getElementById("demo").innerHTML = pos;
• </script></body></html>
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript Regular Expressions</h2>
• <p>Search a string for " Web", and display the position
of the match:</p>
• <p id="demo"></p>
• <script>
• let text = " Lets Learn Web Programming!";
• let n = text.search(/web/i);
• document.getElementById("demo").innerHTML = n;
• </script> </body> </html>
• <!DOCTYPE html>
Replace
• <html>
• <body>
• <h1>JavaScript String Methods</h1>
• <p>Replace “II Sem" with “III Semester" in the paragraph below:</p>
• <button onclick=“mymca()”>Try it</button>
• <p id="demo">II Sem!</p>
• <script>
• function mymca()
• {
• let text = document.getElementById("demo").innerHTML;
• document.getElementById("demo").innerHTML =
text.replace("II Sem","III Semester");
• }
What Is a Regular Expression
• A regular expression is a sequence of characters
that forms a search pattern.
• When you search for data in a text, you can use this
search pattern to describe what you are searching
for.
• A regular expression can be a single character, or
a more complicated pattern.
• Regular expressions can be used to perform all
types of text search and text replace operations.
/pattern/modifiers;
• Modifiers can be used to perform case-insensitive more global
searches:

Modifier Description
i Perform case-insensitive matching
Perform a global match (find all matches
g rather than stopping after the first
match)
m Perform multiline matching
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript Regular Expressions</h2>
• <p>Do a case-insensitive search for "MCA" in a
string:</p>
• <p id="demo"></p>
• <script>
• let text = "MCA STUDENTS";
• let result = text.match(/mca/i);
• document.getElementById("demo").innerHTML = result;
• </script> </body> </html>
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript Regular Expressions</h2>
• <p>Do a global search for "is" in a string:</p>
• <p id="demo"></p>
• <script>
• let text = "Is this. all there is?";
• let result = text.match(/is/g);
• document.getElementById("demo").innerHTML = result;
• </script> </body> </html>
• <!DOCTYPE html>
• <html> <body>
• <h2>JavaScript Regular Expressions</h2>
• <p>Do a multiline search for "our" at each line in a
string:</p>
• <p id="demo"></p>
• <script>
• let text = "\n our students \n our class?";
• let result = text.match(/our/m);
• document.getElementById("demo").innerHTML = "Result
is: " + result;
• </script> </body> </html>
Asynchronous GET/POST using XMLHttpRequest
To send a request to a server, open() and send() methods of the
XMLHttpRequest object can be used as follows:
var xhttp = new XMLHttpRequest();
xhttp.open("", "ajax_info.txt", true);
xhttp.send();
❖ Method ❖ Description
❖ Specifies the type of request

❖ open(method, url, async) method: the type of request: GET or POST


url: the server (file) location
async: true (asynchronous) or false (synchronous)
❖ send() ❖ Sends the request to the server (used for GET)
❖ send(string) ❖ Sends the request to the server (used for POST)
The url parameter of the open() method, is an address
to a file on a server:

xhttp.open("GET", "ajax_test.txt", true);

The file can be any kind of file, like .txt and .xml, or
server scripting files like .asp and .php (which can
perform actions on the server before sending the
response back).
• Server requests should be sent asynchronously.
• The async parameter of the open() method should be
set to true:
xhttp.open("GET", "ajax_test.asp", true);

• By sending asynchronously, the JavaScript does not


have to wait for the server response, but can instead:
• execute other scripts while waiting for server
response.
• deal with the response after the response is
ready.
• The default value for the async parameter is async =
true.
• Synchronous XMLHttpRequest (async = false) is not
recommended because the JavaScript will stop
executing until the server response is ready.
• If the server is busy or slow, the application will hang
or stop.
GET and POST
GET is simpler and faster than POST, and can be used in
most cases.
However, always use POST requests when:

• A cached file is not an option (update a file or database on


the server).
• Sending a large amount of data to the server (POST has no
size limitations).
• Sending user input (which can contain unknown characters),
POST is more robust and secure than GET.

Example for GET: Refer Slide No. 12


GET methods→ open() and Send
POST method property→ responceText
Ajax Java Example with Database
• Steps to create ajax example with database through jsp
Step 1: Load the org.json.jar file
Step 2: Create input page to receive any text or number
Step 3: Create server side page to process the request
Step 2: Create input page to receive any text or
number
• In this page, create a form to get input from the
user. When user press any key, sendInfo() function
is called.
• The getInfo() function have called whenever ready
state changes. It writes the returned data in the
web page dynamically by the help of innerHTML
property.
<html> <head> <script>
var request;
function sendInfo()
{
var v=document.vinform.t1.value;
var url="index.jsp?val="+v;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}
catch(e)
{
alert("Unable to connect to server");
}
}
function getInfo()
{
if(request.readyState==4)
{
var val=request.responseText;
document.getElementById('amit').innerHTML=val;
} }
</script> </head> <body>
<marquee><h1>This is an example of ajax</h1></marquee>
<form name="vinform">
Enter id:<input type="text" name="t1" onkeyup="sendInfo()">
</form>
<span id="amit"> </span> </body> </html>
Create Server Side Page To Process The Request
<%@ page import="java.sql.*"%>
<%
String s=request.getParameter("val");
if(s==null || s.trim().equals(""))
{
out.print("Please enter id");
}
Else
{
int id=Integer.parseInt(s);
out.print(id);
Try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mdb","root","root");
PreparedStatement ps=con.prepareStatement("select * from emp where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
out.print(rs.getInt(1)+" "+rs.getString(2));
}
con.close();
}catch(Exception e){e.printStackTrace();}
}
%>

You might also like