The document describes how to use Ajax techniques to fetch data from a text file and display it on a web page without refreshing the page. It includes:
1) An HTML file with a button that, when clicked, calls a JavaScript function to fetch the data.
2) The JavaScript function uses the XMLHttpRequest object to make an asynchronous GET request to the text file and display the response in a <div> element.
3) It analyzes how the XMLHttpRequest object is used to open a connection, handle the response, and display the fetched data on the page without reloading.
JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.
JSON Is Not XML.
JSON is a simple, common representation of data.
Describes a Web development technique for creating interactive Web applications using a combination of HTML (or XHTML) and Cascading Style Sheets for presenting information; Document Object Model (DOM).
JavaScript, to dynamically display and interact with the information presented; and the XMLHttpRequest object to interchange and manipulate data asynchronously with the Web server.
It allows for asynchronous communication, Instead of freezing up until the completeness, the browser can communicate with server and continue as normal.
Web Integration Patterns in the Era of HTML5johnwilander
Presentation given at OWASP BeNeLux November 2012 and GeekMeet Stockholm January 2013. Covers secure and robust integration patterns for the web using cross origin resource sharing (CORS), sandboxed iframes, and the postMessage API.
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
The world of open source libraries and tools is vast for Android developers. Writing apps using solely Android SDK is impractical. Libraries can help you in many ways. They can speed up your development, save you creating boilerplate code and dealing with platform fragmentation, simplify your code and make it more readable and maintainable. In the talk I’m showing how several truly useful libraries can help a developer.
Presented at MobCon Europe 2017.
Data Management 3: Bulletproof Data ManagementMongoDB
"This session focuses on delivering operationally robust deployments of MongoDB via specific design capabilities and varying data feeds. Learn how to use services or driver wrappers to unify design patterns for managing data. This talk will address the following questions:
How do you enforce a schema?
How do you redact or remove sensitive data in queries and feeds?
How do you detect and police ""out of profile"" queries and make sure they do not threaten your system?"
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
This talk is based on heated discussions about the syntax of asserts. Do you like the good old `assertNotEquals(id, c.getId())` or do you prefer something fancier like `assertThat(id, is(not(equalTo(c.getId()))))`? We will take a quick look at the differences between asserts in JUnit, TestNG, Hamcrest, fest, AssertJ, and Spock. This topic is at least as important as Vim vs Emacs and tabs vs spaces!
Ajax is the web's hottest user interface. Struts is Java's most popular web framework. What happens when we put Ajax on Struts?
In this session, we look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.
During the session, we will cover
* How to integrate an Ajax UI with Struts 2
* Basics of the Yahoo User Interface (YUI) Library
* Business services Struts can provide to an Ajax UI
Who should attend: Ajax developers who would like to utilize Struts as a back-end, and Struts developers who would like to utilize Ajax as a front-end.
To get the most from this session, some familiarity with an Ajax library, like YUI or Dojo, is helpful.
Introduction to programming with Ajax. Covers XMLHttpRequest, XML, JSON, JavaScript, HTML, CSS, Dom Scripting, Event Handling with some examples from YUI library. I gave this talk a dozen or more times in workshops throughout the U.S. & in Amsterdam (AdaptivePath, Yahoo!, Federal Reserve, Ultimate Software, VeriSign, United Online, etc.) . Jan 2006 - Feb 2007.
JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.
JSON Is Not XML.
JSON is a simple, common representation of data.
Describes a Web development technique for creating interactive Web applications using a combination of HTML (or XHTML) and Cascading Style Sheets for presenting information; Document Object Model (DOM).
JavaScript, to dynamically display and interact with the information presented; and the XMLHttpRequest object to interchange and manipulate data asynchronously with the Web server.
It allows for asynchronous communication, Instead of freezing up until the completeness, the browser can communicate with server and continue as normal.
Web Integration Patterns in the Era of HTML5johnwilander
Presentation given at OWASP BeNeLux November 2012 and GeekMeet Stockholm January 2013. Covers secure and robust integration patterns for the web using cross origin resource sharing (CORS), sandboxed iframes, and the postMessage API.
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
The world of open source libraries and tools is vast for Android developers. Writing apps using solely Android SDK is impractical. Libraries can help you in many ways. They can speed up your development, save you creating boilerplate code and dealing with platform fragmentation, simplify your code and make it more readable and maintainable. In the talk I’m showing how several truly useful libraries can help a developer.
Presented at MobCon Europe 2017.
Data Management 3: Bulletproof Data ManagementMongoDB
"This session focuses on delivering operationally robust deployments of MongoDB via specific design capabilities and varying data feeds. Learn how to use services or driver wrappers to unify design patterns for managing data. This talk will address the following questions:
How do you enforce a schema?
How do you redact or remove sensitive data in queries and feeds?
How do you detect and police ""out of profile"" queries and make sure they do not threaten your system?"
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
This talk is based on heated discussions about the syntax of asserts. Do you like the good old `assertNotEquals(id, c.getId())` or do you prefer something fancier like `assertThat(id, is(not(equalTo(c.getId()))))`? We will take a quick look at the differences between asserts in JUnit, TestNG, Hamcrest, fest, AssertJ, and Spock. This topic is at least as important as Vim vs Emacs and tabs vs spaces!
Ajax is the web's hottest user interface. Struts is Java's most popular web framework. What happens when we put Ajax on Struts?
In this session, we look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.
During the session, we will cover
* How to integrate an Ajax UI with Struts 2
* Basics of the Yahoo User Interface (YUI) Library
* Business services Struts can provide to an Ajax UI
Who should attend: Ajax developers who would like to utilize Struts as a back-end, and Struts developers who would like to utilize Ajax as a front-end.
To get the most from this session, some familiarity with an Ajax library, like YUI or Dojo, is helpful.
Introduction to programming with Ajax. Covers XMLHttpRequest, XML, JSON, JavaScript, HTML, CSS, Dom Scripting, Event Handling with some examples from YUI library. I gave this talk a dozen or more times in workshops throughout the U.S. & in Amsterdam (AdaptivePath, Yahoo!, Federal Reserve, Ultimate Software, VeriSign, United Online, etc.) . Jan 2006 - Feb 2007.
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
The first of its kind Web Technology Conference on Open Source Technology, WebOSS '07 was organised in Kolkata on Sat, 13th Oct 07 and I spoke at the event as one of the participants on "Building Applications using AJAX". Here I will share my presentation.
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
This is the 1988 issue of The Elphinstonian, the annual magazine of Elphinstone College, Mumbai. This is the special issue to commemorate the Century of the Elphinstone College Building in Mumbai.
What is gravitation, Newton's law of gravitation, projection of a satellite, derivations, weightlessness explained, change in value of g with altitude, time period of a satellite, binding energy, escape velocity of a satellite,
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
This is a 14 page question bank on the chapters of Electrostatics. This is based on the syllabus of most Board exams such as CBSE, ISCE and state boards.
Extremely important topic for Digital electronics, digital circuits, computer architecture and computer science.
Full video is available on Youtube: https://youtu.be/oyOaXqx06pY
This video explains the method of converting a decimal number to a binary number. Many solved examples are given here and also two exercises which you can attempt on your own and then check the answers.
I have also discussed the concept of LSB (least significant bit) and MSB (most significant bit), and also least significant digit (LSD) and most significant digit (MSD).
This topic is important for following courses: class 11 and 12 computer science of all state boards, class 11 and 12 physics, BSc Computer science, BSc IT, MCA (Masters degree in Computer Applications), BTech, BE (First Year), and many competitive examinations.
Free Lectures on YouTube for IGCSE Physics for the syllabus effective 2020-21. These lectures cover the syllabus of IGCSE and a major part of GCSE syllabus also.
1. The Hidden Meaning of Words in Science Question Papers
2. Scientific Notation or Powers of Ten Notation
3. Units and Base Quantities
4. What is Physics?
What is Cyber Law? Why is cyber security law needed? International cyber law. What is copyright? What are security, controls, privacy, piracy and ethics? Code of ethics for computer professionals. What is cyber insurance?
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Ajax chap 2.-part 1
1. Chap 3. Programming in Ajax 1
3. Programming in Ajax - Part I
1. Write program that asks the user to click a button, fetches data from a text file using Ajax
techniques, and displays that data in the same web page without refreshing the whole page.
The HTML file (AJAX1.HTML) is shown below:
<html>
<head>
<title>Ajax at Work</title>
<script language = "javascript">
var xhobj = false;
if(window.XMLHttpRequest)
{
xhobj = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhobj = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(xhobj)
{
var obj = document.getElementById(divID);
xhobj.open("GET", dataSource);
xhobj.onreadystatechange = function()
{
if(xhobj.readyState == 4 && xhobj.status == 200)
{
obj.innerHTML = xhobj.responseText;
}
}
xhobj.send(null);
}
}
</script>
</head>
<body>
<h1>Fetching data with Ajax</h1>
<form>
<input type = "button" value = "Display Message " onclick =
"getData('http://localhost/AJAX/data.txt', 'targetDiv')">
</form>
<div id = "targetDiv">
<p>The data fetched will go here</p>
</div>
</body>
</html>
The text file is data.txt and it has just one line in it: Hooray!! Hooray!! This is displayed by Ajax
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
2. 2 Programming in Ajax
Analysis of the above program:
1. Consider the body of the HTML document. We display a button on this page by creating a <form>
element.
2. We have also created a <div> element called “tartgetDiv” in which the fetched data will be displayed.
3. When the user clicks on this button, a JavaScript function called getData() is called. We use the onclick()
event for this purpose.
4. The getData() function is passed 2 strings :
a. The name of the text file DATA.TXT to fetch from the server, and
a. The name of the <div> element to display the fetched text in.
5. In the <head> section of the HTML document we create the JavaScript code starting with the line :
<script language = "javascript">
6. Within the script, we create a variable to store the data, and an XMLHttpRequest object is created to set
up a connection with the server and retrieve the data from the text file.
7. The code to create the XMLHttpRequest object is outside any function, so this code runs immediately as
the page loads.
8. We create a variable for this object var xhobj = false; This variable is initialized to the value ‘false’ so
that the script can check later whether the variable was created.
9. The XMLHttpRequest object is part of the browser’s window object. So to check whether the
XMLHttpRequest object is ready to use, we use the if statement. If XMLHttpRequest object is available,
we can create the object as follows, for non_IE browsers:
if(window.XMLHttpRequest)
{
xhobj = new XMLHttpRequest();
}
If we are working with Internet Explorer, we can create an XMLHttpRequest object like this:
else if (window.ActiveXObject)
{
xhobj = new ActiveXObject("Microsoft.XMLHTTP"); }
Now we have the XMLHttpRequest object.
10. The onreadystatechange property holds the name of the event handler that should be called when
the value of the readyState property changes.
11. The readyState property holds the state of the request.
12. The getData() function will be used to actually fetch the text data from the file.
13. We first check that there is a valid object with the statement if (xhobj)
14. If the object creation hadn’t worked, then this variable will hold a value ‘false’ and the condition would
become false.
15. Now we have the xhobj variable. This object has a method called “open()”. We will use that method to
use the URL we want. Syntax of open() method is:
open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]])
• method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD
• URL – the requested URL
• asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is
‘true’ (asynchronous)
16. The URL we want to fetch is passed to the getData() function as the dataSource argument
17. To open a URL we can use the GET, POST or PUT methods. But in this example we use the GET
method.
18. Now, xhobj is ready to use the URL we have given. But it does not connect to that file.
19. By default the connection to this file is made asynchronously. It means that this statement does not wait
until the connection is made and the data is finished downloading
20. The XMLHttpRequest object has a property called onreadystatechange that lets us handle
asynchronous loading operations.
21. If we assign the name of a JavaScript function to this property, that function will be called each time the
XMLHttpRequest object’s status changes.
xhobj.onreadystatechange = function()
22. We have used a shortcut to assign a JavaScript function to the onreadystatechange property. We
have created an anonymous function because the function does not have any name. Such a function is
created on the fly, just by using the keyword function(). Then we define the body of this function in
curly braces. This new anonymous function will be called whenever the XMLHttpRequest object
undergoes a change.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
3. Chap 1. Introduction to Ajax 3
23. The XMLHttpRequest object has 2 properties that are important for us. The readyState property
that tells us how the data downloading is progressing. The readyState property can have these
values:
0 – uninitialized
1 – loading
2 – loaded
3 – interactive
4 – complete
We have used the value 4, which means the data is downloaded.
24. The status property tells us the status of the download itself. It is the standard HTTP status code that
the browser got for the URL we supplied. The possible values of status are:
• 200 – all OK
• 400 – Bad request
• 403 – Forbidden
• 404 – Not found
• 408 – request time out
• 414 – Requested URL too long
So here is the meaning of the statement
if(xhobj.readyState == 4 && xhobj.status == 200)
It means we are checking that the data has been downloaded completely (readyState = 4) and
everything went ok with the request to the server (status = 200)
25. The data has been fetched from the server. Now to get the data on the Web page we use one of these
techniques:
– If we want to treat the data as standard text, we use the object’s responseText property.
– If the data is in XML format, we can use the responseXML property.
26. To make the test appear on the page, we assign that text to the <div> element whose ID is targetDiv.
This ID was passed to the getData() function.
27. To connect to the server to get the response we use the send() method. When we are using the GET
method, we send a value of null to connect to the server and request the data using the XMLHttpRequest
object.
xhobj.send(null);
28. The send() method actually downloads the data so that the anonymous function can handle that data.
2. Write a note on the XMLHttpRequest object. What are its properties and methods?
1. The XMLHttpRequest object is created to set up a connection with the server and retrieve the data from
the text file from the web server without reloading the entire page.
2. This objet supports any text and XML formats.
3. It can be used to make requests over both HTTP and HTTPS protocols.
4. The XMLHttpRequest object is part of the browser’s window object.
5. We can create the XMLHttpRequest object as follows for non-IE browsers:
if(window.XMLHttpRequest)
{
xhobj = new XMLHttpRequest();
}
For IE browser, we create the XMLHttpRequest object as follows:
if (window.ActiveXObject)
{
xhobj = new ActiveXObject("Microsoft.XMLHTTP");
}
The first method shown above also works for IE 8 (yes, it has been tested by me!)
Events of XMLHttpRequest object for Internet Explorer
Property Description
onreadystatechange Holds the name of the event holder that should be called when the value of the
readyState property changes.
ontimeout This event is raised when there is an error that prevents the completion of the
request.
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
4. 4 Programming in Ajax
Properties of XMLHttpRequest object for Internet Explorer
Property Description
readyState Holds the state of the request
responseBody Holds a response body which is one way HTTP responses can be returned.
responseStream Holds a response stream ( a binary stream)
responseText Holds the response body as a string
responseXML Holds the response body as XML
Status Holds the HTTP status code returned by a request
statusText Holds the HTTP response status text
Timeout Gets or sets the timeout value.
Methods of XMLHttpRequest object for Internet Explorer
Method Description
Abort Aborts the HTTP request
getAllResponseHeaders Gets all the HTTP headers
getResponseHeader Gets the value of an HTTP header
Open Opens a request to a server
Send Sends an HTTP request to the server
setRequestHeader Sets the name and value of an HTTP header
The open() method:
Syntax:
open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]])
• method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD
• URL – the requested URL
• asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is
‘true’ (asynchronous)
The send() method:
Syntax:
object.send( [var])
This method is synchronous or asynchronous, depending on the value of the asyncFlag in the open method call. If
asynchronous, this call returns immediately.
The onreadystatechange event:
This holds the name of the event holder that should be called when the value of the readyState property changes.
The following script shows how to set an asynchronous event handler that alerts the user when the readyState
property of the request reaches ‘complete’(value 4).
xhobj.onreadystatechange = function()
{
if(xhobj.readyState == 4 && xhobj.status == 200)
{
alert('Transfer complete.');
}
}
The responseText property:
It retrieves the response body as a string. It is a rad-only property and has no default value.
Syntax
sBody = object.responseText
3. What are the steps in creating an Ajax program?
The various steps in creating an Ajax program are as follows:
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
5. Chap 1. Introduction to Ajax 5
1. Create an instance of the XMLHTTPRequest object that will work across different browser implementations.
This object is part of the browser’s window. We create the object as follows:
var xhobj = false;
if(window.XMLHttpRequest)
{
xhobj = new XMLHttpRequest();
}
2. Prepare a request using the onreadystatechange event handler, the open method, and the send
method.
xhobj.onreadystatechange = function()
3. Process the response from the server through the properties readyState, status, responseText, and
sometimes responseXML.
if(xhobj.readyState == 4 && xhobj.status == 200)
{
obj.innerHTML = xhobj.responseText;
}
4. How are asynchronous requests handled in Ajax?
1. The XMLHttpRequest object is the core of the Ajax engine.
2. It is the object that enables a page to get data from (using the GET method) or post data to (using the POST
method) the server as a background request.
3. The browser is not refreshed during this process.
4. The XMLHttpRequest object eliminates the need to wait for the server to respond with a new page for each
request. The user can continue to interact with the page while the requests are made in the background.
5. The most common formats in which we can receive data from XMLHttpRequest object is text or XML
formats.
6. This object has a method called “open()”. We use that method to open the URL we want. Syntax of open()
method is:
open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]])
• method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD
• URL – the requested URL
• asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous.
Default is ‘true’ (asynchronous)
5. Write a note on the XMLHttpRequest readyState property.
The readyState property holds the status of the request sent by the client. This property has 4 possible values
as follows:
0 – uninitialized: The object has been created but not initialized (i.e. the open () method has not been called)
1 – loading: Server connection has been established. A request has been opened but the send method has not
been called.
2 – loaded: A request s received. The send method has been called. No data is available yet.
3 – interactive or processing request: A request has been opened. Some data is received but not all.
4 – complete or request finished and response is ready.
This is a read-only property and it does not have a default value. When the value of this property becomes we can
obtain the responseText property to obtain the text returned by the server. It is used along with the status property.
6. Write a note on the status property of the XMLHttpRequest object.
The status property tells us the status of the download. It is the standard HTTP status code that the browser got
for the URL we supplied. The possible values of status are:
• 200 – all OK
• 400 – Bad request
• 403 – Forbidden
• 404 – Not found
• 408 – request time out
• 414 – Requested URL too long
To make sure that the data has been downloaded completely and everything went OK, we must check that the
readyState property has the value 4 and the status property has the value 200. This is doe as follows:
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
6. 6 Programming in Ajax
if(xhobj.readyState == 4 && xhobj.status == 200)
{
obj.innerHTML = xhobj.responseText;
}
7. Explain the innerHTML property.
1. Each HTML element has an innerHTML property that defines both the code and the text that appears
between the element’s opening and closing tags.
2. Before we can change the text that appears within the element tags, we must give an id (like a name) to this
element.
3. Once the id has been given, we can use the getElementById function
4. The innerHTML property sets or returns the inner HTML of an element.
5. The innerHTML property can contain text and HTML elements.
6. When this property is set, the given string completely replaces the existing content of the object.
7. If the string contains HTML tags, the string is parsed and formatted.
Example:
<html>
<head>
<script type="text/javascript">
function changeText()
{
document.getElementById('boldStuff').innerHTML =
"<font color='blue'>My Dearest Friends</font>";
}
</script>
</head>
<body>
<p>Welcome to the site <b id='boldStuff'>dude</b></p>
<input type='button' onclick='changeText()' value='Change Text'/>
</body>
</html>
8. Write Ajax code to display three images on a web page. When the user moves the mouse over any
image, the application fetches the text for that mouseover event using Ajax.
We first create the HTML page AJAX2.HTML:
<html>
<head>
<title>Ajax at Work</title>
<script language = "javascript">
var xhr = false;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(xhr)
{
var obj = document.getElementById(divID);
xhr.open("GET", dataSource);
xhr.onreadystatechange = function()
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
7. Chap 1. Introduction to Ajax 7
{
if(xhr.readyState == 4 && xhr.status == 200)
{
obj.innerHTML = xhr.responseText;
}
}
xhr.send(null);
}
}
</script>
</head>
<body>
<h1>Interactive Mouseovers</h1>
<img src = "yahoo.jpg"
onmouseover="getData('http://localhost/AJAX/yahoo.txt','targetDiv')">
<img src = "rediff.jpg"
onmouseover="getData('http://localhost/AJAX/rediff.txt','targetDiv')">
<img src = "altavista.jpg"
onmouseover="getData('http://localhost/AJAX/altavista.txt','targetDiv')">
<div id = "targetDiv">
<p>Search the web with these search engines</p>
</div>
</body>
</html>
The HTML file displays 3 images of three popular search engines in the <body> element. We connect the
getData() function with the onmouseover() event. The getData function will fetch the text from the respective file.
Next we create the 3 text files. The contents of each text file are shown:
File:Altavista.txt, Content: <font color = 'red'>Altavista - was the king once upon a time</font>
File:Rediff.txt, Content: Rediffmail portal - Recently main features have been updated.
File:Yahoo.txt, Content: Yahoo portal - Mail, News, Chat, and more
9. What is server-side scripting? Which are the server-side scripting languages?
1. Server-side scripts are programs that can run on the server.
2. Normally when a browser requests an HTML file, the server returns the file, but if the file contains a server-
side script, the script inside the HTML file is executed by the server before the file is returned to the browser
as plain HTML.
3. Server-side scripts can do the following:
a. Dynamically change the content of a web page
b. Return data from a database
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
8. 8 Programming in Ajax
c. Customize the web page so as to make it more useful; for the user.
d. Provide security since the server-side code cannot be viewed from the browser.
4. The two common scripting languages are ASP and PHP.
10. Write the Ajax code that uses a PHP script on a server to display a message when the user clicks
on a command button.
The PHP file is DATA.PHP shown below:
<?php
echo ‘This text was fetched using Ajax.’;
?>
The HTML file AJAX3.HTML is as follows:
<html>
<head>
<title>Ajax and PHP at work</title>
<script language = "javascript">
var xhr = false;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(xhr)
{
var obj = document.getElementById(divID);
xhr.open("GET", dataSource);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
obj.innerHTML = xhr.responseText;
}
}
xhr.send(null);
}
}
</script>
</head>
<body>
<H1>Fetching data with Ajax and PHP</H1>
<form>
<input type = "button" value = "Display Message"
onclick = "getData('data.php', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched data will go here.</p>
</div>
</body>
</html>
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
9. Chap 1. Introduction to Ajax 9
11. Write the code to show how to retrieve data from an XML document.
Consider the following XML code in the AJAX5NOTE.XML:
<note>
<to>Raja </to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The Ajax code to retrieve this XML file is as follows (AJAX5.HTML):
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
document.getElementById('A1').innerHTML = xhr.status;
document.getElementById('A2').innerHTML = xhr.statusText;
document.getElementById('A3').innerHTML = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.send(null);
}
</script>
</head>
<body>
<h2>Retrieving data from XML file</h2>
<p><b>Status: </b><span id="A1"></span></p>
<p><b>Status text: </b><span id="A2"></span></p>
<p><b>Response: </b><span id="A3"></span></p>
<button onclick = "loadXMLDoc('/note.xml')">
Get XML data</button>
</body>
</html>
mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
10. 10 Programming in Ajax
12. Explain the techniques by which Ajax passes data to the server.
1. Ajax can pass data to the server either by the GET or by the POST method.
2. If we use the GET method, the data sent is public as it can be seen in the browser’s address bar. This method
uses URL encoding. It means that the data that is being sent is appended to the actual URL.
3. Suppose we have a text field named ‘a’ that contains the number 5, another text filed called ‘b’ that contains
the text “centuries”, then all this data will be encoded and added to the URL. A question mark is ended to
the end of the URL and data is added in the form name=value. Spaces are converted into a + sign and we
separate the pairs of name=data by the ‘&’ sign.
4. So the complete URL becomes: www.servername.com/scriptname?a=5&b=centuries
5. All data sent this way is text, even if we send numbers.
6. The JavaScript escape function will encode data for appending to the end of the URL. This function will
also convert spaces into the + symbol.
7. When we pass data to a URL by using the POST method, it is encoded internally and data is more
secure.
PROGRAMMING EXERCISES
Modify the program in Q 1 so that it displays an alert box when the transfer of data is complete.
Modify the following if statement as shown below:
if(xhobj.readyState == 4 && xhobj.status == 200)
{
alert('Transfer complete.');
}
Modify the program in Q 1 so that the page displays 2 command buttons. When the user clicks
on the first button, the program fetches data from a file data1.txt. When the user clicks on the
second command button, the program should fetch data from the file data2.txt and display that
data in the same web page without refreshing the whole page.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com