0% found this document useful (0 votes)
31 views31 pages

WT Lab Manual

Uploaded by

Vasanth B
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)
31 views31 pages

WT Lab Manual

Uploaded by

Vasanth B
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/ 31

Ex.

N0: 01
Create a web page with the following using HTML a. To embed a map in a web
Date: b. To fix the hot spots in that map c. Show all the related information when the
hotspots are clicked.

OBJECTIVE:

To create a web page with the following using HTML


a. To embed a map in a web page
b. To fix the hot spots in that map
c. Show all the related information when the hot spots are clicked.

ALGORITHM:

1. Start the program.


2. Get the india map image and link it to the package.
3. Fix the hotspots in that image.
4. Map the reference of the hotspots in the image.
5. Mention the derived link.
6. Click the link to get the desired image.
7. Stop the program.

IMPLEMENTATION:
Main.html
<!DOCTYPE html>
<html>
<head>
<title>MAP</title>
</head>
<body bgcolor="#gop6876cgdt5564ss">
<img src="indiamap.jpg" alt=india usemap="#map" />
<map name=map>
<area target="_blank" alt="TamilNadu" href="tamilnadu.html"
coords="239,771,333,716,321,802,257,871" shape="poly">
<area target="_blank" alt="Kerala" href="kerala.html"
coords="242,864,245,816,217,763,184,737" shape="poly">
<area target="_blank" alt="Karnataka" href="karataka.html"
coords="180,725,249,760,243,587,158,648" shape="poly">
<area target="_blank" alt="Odisha" href="orissa.html"
coords="497,426,545,372,573,442,537,470" shape="poly">
<area target="_blank" alt="Maharashtra" href="maharastra.html"
coords="149,644,122,514,333,473,341,522" shape="poly">
<area target="_blank" alt="Madhya Pradesh" href="madhyapradesh.html"
coords="191,392,177,471,354,469,381,376" shape="poly">
1
</map>

</body>
</html>

Tamiladu.html
<html>
<head>
<body bgcolor="#fggbhjgdhg" />
<center>
<h2>it is a tamilnadu,here maximum tamilan living and capital of tamilnadu is</h2>
<h1>chennai<h1>
</center>
</head>
</html>

Kerala.html
<html>
<head>
<body bgcolor="#7674dshddf" />
<center>it is a kerala,here maximum malaiyalees living and capital of kerala is
<h1>Thiruvananthapuram</h1>
</center>
</head>
</html>

Karataka.html
<html>
<head>
<body bgcolor="#7674dshddf" />
<center>it is a karnataka,here maximum kannadam living and capital of karnataka is
<h1>Bangalore</h1>
</center>
</head>
</html>

Madhyapradesh.html
<html>
<head>
<body bgcolor="blue" />
<center>it is a madhyapradesh,here maximum maratiyam living and capital of
madhyapradesh is <h1>BHOPAL</h1>
</center>
</head>
</html>

Maharastra.html
<html>

2
<head>
<body bgcolor="blue" />

<center>it is a maharashtra,here maximum maratiyam living and capital of maharashtra is


<h1>Mumbai</h1>
</center>
</head>
</html>

Orissa.html
<html>
<head>
<body bgcolor="blue" />
<center>
<h2>it is a orissa,here maximum oreya living and capital of orissa is</h2>
<h1>Bhubaneswar</h1>
</center>
</head>
</html>

OUTPUT:

3
RESULT:

Thus, the web page has been created, the image embedded with hotspots, and the linking pages
have been successfully verified.

4
Ex.N0: 02
Create a web page with all types of Cascading style sheets.
Date:

AIM:
Create a web page with the following Cascading style sheets.

b. Inline style sheets.


Use our college information for the web pages.

ALGORITHM:
1. Start the program.
2. Create a web page with framesets consisting two frames.
3. In the first frame include the links.
4. In the second frameset display the webpage of the link.
5. Create a external style sheets.
6. Create a inline and internal style and make a link to the external style sheet.
7. Stop the program

SOURCE CODE:
<html>
<head>
<title>Cascading Style Sheets</title>
</head>
<body alink="blue" vlink="brown">
<h1><u><b>
<font face="Monotype corsiva" color="red"> Different types of Cascading
Style Sheets</font>
</b></u></h1>
<br />
<font face="Arial" size="6">
<a href="inline.html" style="text-decoration :none;"> 1. Inline Style Sheet</a><br
/>
<a href="embedded.html" style="text-decoration :none;"> 2. Embeded Style
Sheet</a><br />
<a href="external.html" style="text-decoration :none;"> 3. External Style
Sheet</a><br />
<a href="import.html" style="text-decoration :none;"> 4. Imported Style
Sheet</a><br />
</font>
</body>
</html>

5
Inline.html
<html>
<head>
<title>Inline Style Sheet</title>
</head>
<body>
<ol class="decimal">
<h1 style="font-family :Monotype Corsiva ;background-color:antiquewhite ;">
<li> Inline Style Sheet</li>
</h1>
<h3>
<p style="text-indent :30pt;color:blue;font-family :arial;">Inine Style is the
style attached to one
specific element. The style is specified directly in the start tag as a
value of the style attribute
well apply exclusively to this specific element occurrence.
</p>
</h3>
</ol>
</body>
</html>

Embedded html
<html>
<head>
<title>Embeded Style Sheet</title>
<style type="text/css">
ol {
list-style-type: decimal
}
h1 {
text-align: left;
background: antiquewhite;
font-family: monotype corsiva;
color: red
}
h3 {
text-align: right;
font-family: arial;
color: blue
}
</style>
</head>
<body>
<ol class="lroman">
<h1>
<li>Embedded style sheet</li>
</h1>
<br />
Embedded style is the style attached to one specific document. The information is
specified as a content of the
style element inside the head element and wil apply to the entire documents.
</h3>
</ol>
</body>
</html>

OUTPUT:
RESULT:
Thus, the web page has been successfully created using all types of cascading style sheets, and the
output has also been verified.
Ex. N0: 03
1. Client Side Scripts for Validating Web Form Controls using DHTML.
Date:

AIM
Validate the Registration, user login, user profile using JavaScript.

ALGORITHM:
1. Create JavaScript functions (one for each input field whose value is to validate)
which check whether a value submitted by user passes the validation.
2. Functions are called from another function.
3. Sets the focus to the input field until the user supplies a valid value.
4. When the user does so, it proceeds and can supply value to the next available field.
5. The later JavaScript function created is called on the onsubmit event of the form.

PROGRAM:
JavaScript code for validation

<!DOCTYPE html>
<html>

<head>
<title>Form Validation</title>
<script type="text/javascript">
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;

if (name == "") {
alert("Name must be filled out");
return false;
}

if (email == "") {
alert("Email must be filled out");
return false;
}
if (password == "") {
alert("Password must be filled out");
return false;

}
}
</script>
</head>

<body>
<h1>Form Validation</h1>
<form name="myForm" onsubmit="return validateForm()" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>

<input type="submit" value="Submit">


</form>
</body>

</html>

OUTPUT:

Result:
Thus, the given form was successfully validated.
Ex. N0:2.04 Install TOMCAT web server. Convert the static web pages of programs into dynamic web
pages using servlets (or JSP) and cookies. Hint: Users information (user id, password, credit
Date: card number) would be stored in web.xml. Each user should have a separate Shopping Cart.

Aim:
To convert the static web pages into dynamic web pages using servlets (or JSP) and cookies.

Procedure:
Step1: we will create ahtml form for entering the user name,password and card ID.
Step2: From the above HTML form, the servlet program is invoked in which the validity of the user
name,password and card id is checked.if it is a valid user then the welcome message will be displayed
otherwise the <invalid user= message will be displayed. In this servlet we set the cookies in which the
current user name is stored.
Step3: compile the above servlet Login servlet.java and copy its class file in tomcats folder at
c:\tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.We must store he user information such as user name,password
and card id in the web.xml using init-param.
Step4: On successful login , the information from the cookie is checked and shopping cart page for
corressponding user can be displayed.
Step5: Compile the above servlet LoginSuccess.java and copy its class file in the tomcat's folder at
c:\tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.
Step6: Start tomcat web server.Open the web browser and display the login form created in step1.

Index.html
<html>
<head>
<body>
<form action="http://localhost:8084/ddd/LoginServlet" method="post"> Enter username:
<input type="text" value""name="user">
<br>
Enter Password:
<input type="password" value""name="password">
<br>
Enter Card ID:
<input type="text" value""name="cardID">
<br>
<br> <br> <br>
<input type="submit" value="login">
</form>
</body>
</head>
</html>
Loginservlet.html
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String usr=request.getParameter("user");
String pwd=request.getParameter("password");
String card=request.getParameter("cardID");
boolean flag=true;
String[] userID=getInitParameter("usernames").split(",");
String[] password=getInitParameter("passwords").split(",");
String[] cardids=getInitParameter("cardIDs").split(",");
for(int i=0;i<userID.length;i++)
{
if(userID[i].equals(usr)&&password[i].equals(pwd)&&cardids[i].equals(card))
{
flag=false;
Cookie MyCookie=new Cookie("CurrentUser", usr); MyCookie.setMaxAge(60*60);
response.addCookie(MyCookie);
response.sendRedirect("http://localhost:8084/ddd/LoginSuccess");
}
}
if(flag==true)
{
out.print("Error");
out.println("<h4>Invalid user,please try again by clicking following
link</h4>");
out.println("<a href='http://localhost:8084/ddd/'>"+"LoginForm.html");
}
}
finally
{
out.close();
}
}
}
LoginSuccess.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginSuccess extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException
{
Cookie[] my_cookies=request.getCookies();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("Login Success");
out.println("<b>");
String userName=null;
if(my_cookies!=null)
{
for(Cookie cookie:my_cookies)
{
if(cookie.getName().equals("currentUser"))
userName=cookie.getValue();
}
}
out.print("<h3>Login Success!!!Welcome</h3>");
out.print("<h2>This is a Shopping cart for"+userName+"</h2>");
out.close();
}
}

Web.xml
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
<init-param>
<param-name>usernames</param-name>
<param-value>user1,user2,user3</param-value>
</init-param>
<init-param>
<param-name>passwords</param-name>
<param-value>pwd1,pwd2,pwd3</param-value>
</init-param>
<init-param>
<param-name>cardIDs</param-name>
<param-value>111,222,333</param-value>
</init-param>
</servlet>

<servlet>
<servlet-name>LoginSuccess</servlet-name>
<servlet-class>LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginSuccess</servlet-name>
<url-pattern>/LoginSuccess</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout> 30 </session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Output:
Result:
Thus, the conversion of the static web pages into dynamic web pages using servlets and
cookies has been executed successfully.
Ex. N0: 05
3. Write programs in Java using Servlets: i. To invoke servlets from HTML forms
Date: ii. Session tracking using hidden form fields and Session tracking for a
hit count

Aim:
To write a Java Program for Session tracking a hit count. This servlet uses session tracking
to count the number of times a client has accessed it.

Procedure:
• Servlet program to keep track of user visiting the page.
• The count is incremented by one when user visits.
• The output displays the greeting message.
• The number of previous access is also displayed.

Program:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
HttpSession session = req.getSession();
String heading;
Integer cnt=(Integer)session.getAttribute("cnt");
if(cnt==null)
{
cnt=new Integer(0);
heading="Welcome you are accessing the page for the first time";
}
else
{
heading="Welcome once again"; cnt=new Integer(cnt.intValue()+1);
}
session.setAttribute("cnt",cnt);
PrintWriter out = res.getWriter();
out.println("<html>"); out.println("<head>");
out.println("</head>"); out.println("<body>");
out.println("<center>"); out.println("<h1>"+heading);
out.println("<h2>The number of previous access="+cnt);
out.println("</center>");
out.println("</body>"); out.println("</html>");
}}

Output:

Result:
Thus, the Java program for session tracking and hit count has been executed successfully.
Ex. N0: 06 Write programs in Java to create three-tier applications using servlets for conducting
on-line examination for displaying student mark list. Assume that student
Date: information is available in a database which has been stored in a database server.

Aim:
To write java servlet programs to conduct online examination and to display student mark list
available in a database

Procedure:

Client:
• In index.html on the client side declare the contents that you like to transfer to the
server using html form and input type tags.
• Create a submit button and close all the included tags.
Server:
• Import all necessary packages
• Define a class that extends servlet
• In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) Create a writer to the response
iii) Get a paratmeter from the request
iv) If its value is equal to right answer then add 5 to mark variable
v) Similarly repeat step
vi) for all parameters
vii) Display the result in an html format using the writer
Student Mark List Database:
• Import necessary to java packages and javax packages and classes
• Create a class that extends HttpServlet and implements ServletException
• and IOException
• In the doGet() method, do the following:
i) Create a PrintWriter object
ii) Open a connection with the data source name
iii) Write a sql query and execute to get the resultset
iv) Display the resultset information in html form

Program:
SERVLET CODE:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{

String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;
int Total=0;
Connection connect;
Statement stmt=null;
ResultSet rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
ServletExcep- tion,IOException
{
try
{
String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," ");
message="Thank you for participating in online Exam";
}
catch(ClassNotFoundException cnfex)
{
cnfex.printStackTrace();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
catch(Exception excp)
{
excp.printStackTrace();
}
Seat_no=request.getParameter("Seat_no");
Name=request.getParameter("Name");
ans1=request.getParameter("group1");
ans2=request.getParameter("group2");
ans3=request.getParameter("group3");
ans4=request.getParameter("group4");
ans5=request.getParameter("group5");
if(ans1.equals("True"))
Total+=2; if(ans2.equals("False")) Total+=2;
if(ans3.equals("True"))
Total+=2;
if(ans4.equals("False"))
Total+=2;
if(ans5.equals("False"))
Total+=2;
try
{
Statement stmt=connect.createStatement();
String query="INSERT INTO student("+"Seat_no,Name,Total"+")
VALUES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query);
stmt.close();
}
catch(SQLException ex){ }
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=cyan>");
out.println("<center>");
out.println("<h1>"+message+"</h1>\n");
out.println("<h3>Yours results stored in our database</h3>");
out.print("<br><br>");
out.println("<b>"+"Participants and their Marks"+"</b>");
out.println("<table border=5>");
try
{
Statement stmt=connect.createStatement();
String query="SELECT * FROM student";
rs=stmt.executeQuery(query);
out.println("<th>"+"Seat_no"+"</th>");
out.println("<th>"+"Name"+"</th>");
out.println("<th>"+"Marks"+"</th>");
while(rs.next())
{
out.println("<tr>");
out.print("<td>"+rs.getInt(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>");
out.print("<td>"+rs.getString(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
catch(SQLException ex){ } finally
{
try
{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(connect!=null)
connect.close();
}
catch(SQLException e){ }
}
out.println("</center>");
out.println("</body></html>");
Total=0;} }
HTML CODE:

<html>
<head>
<title>Database Test</title>
</head>
<body>
<center>
<h1>Online Examination</h1>
</center>
<form action="StudentServlet3.view" method="POST">
<div align="left"><br></div>
<b>Seat Number:</b> <input type="text" name="Seat_no">
<div align="Right">
<b>Name:</b> <input type="text" name="Name" size="50"><br>
</div>
<br><br>
<b>1. Every host implements transport layer.</b><br /> <input
type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<b>2. It is a network layer's responsibility to forward packets
reliably from source to destina-tion</b><br />
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<b>3. Packet switching is more useful in bursty traffic</b><br />
<input type="radio" name="group3"
value="True">True<input type="radio" name="group3"
value="False">False<br> <b>4. A phone network uses packet
switching</b><br /> <input type="radio" name="group4"
value="True">True <input type="radio" name="group4"
value="False">False<br>
<b>5. HTML is a Protocol for describing web contents</b><br /> <input
type="radio" name="group5"
value="True">True
<input type="radio" name="group5" value="False">False<br> <br><br><br>
<center>
<input type="submit" value="Submit"><br><br>
</center>
</form>
</body>
</html>
Output:

Result:
Thus, the Java servlet programs to conduct online examinations and display student
mark lists available in a database were successfully executed and verified.
Ex. N0: 07 Create and save an XML document at the server, which contains 10 users
Information. Write a Program, which takes user Id as an input and returns the
Date: User details by taking the user information from the XML document.

Aim:
To create and save an XML document at the server, which contain ten users
information. To write a program which takes user id as an input and returns the
user details by taking the user information from the XML document.

Procedure:
• Save Students information in the XML file on the specific location.
• Create and establish the connection between html file and XML file.
• Get the user ID as input
• Display the student9s information.

StudentDetails.xml :
<?xml version="1.0" encoding="UTF-8"?>
<Student>
<PersonDetails>
<id>101</id>
<name>Anand</name>
<city>Madurai</city>
<Branch>CSE</Branch>
<Year>I</Year>
</PersonDetails>
<PersonDetails>
<id>102</id>
<name>Anu</name>
<city>Konam</city>
<Branch>CSE</Branch>
<Year>II</Year>
</PersonDetails>
<PersonDetails>
<id>103</id>
<name>Archana</name>
<city>Madurai</city>
<Branch>CSE</Branch>
<Year>I</Year>
</PersonDetails>
<PersonDetails>
<id>104</id>
<name>Monica</name>
<city>Nellai</city>
<Branch>CSE</Branch>
<Year>III</Year>
</PersonDetails>
</Student>
LogIn.html :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript"> function Display() {
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "UserInfo.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
var x = xmlDoc.getElementsByTagName("PersonDetails");
var key_id = document.getElementById("key").value;
for (i = 0; i < x.length; i++)
{
if
(key_id.match(x[i].getElementsByTagName("id")[0].childNodes[0].nodeValue))
j = i;
}

document.write("<h3>User Details are...</h3> <hr> Registeration


ID=");
document.write(x[j].getElementsByTagName("id")[0].childNodes[0].no
deValue);
document.write("</br> Name=");
document.write(x[j].getElementsByTagName("name")[0].childNodes[0].
nodeValue);
document.write("</br> City=");
document.write(x[j].getElementsByTagName("city")[0].childNodes[0].
nodeValue);
document.write("</br> Branch=");
document.write(x[j].getElementsByTagName("Branch")[0].childNodes[0
].nodeValue);
document.write("</br> Year=");
document.write(x[j].getElementsByTagName("Year")[0].childNodes[0].
nodeValue);
document.write("</br> ");
}
</script>
<form name='myform'> Enter ID:
<input type='text' id='key' /><br />
<input type='button' value='submit' onclick='Display()' />
</form>
</body>
</html>

Output:

Result:
Thus, the program that takes a user ID as input and retrieves user details from the
XML document has been successfully executed.
Ex. N0: 08
Write a web service for finding what people think by asking 500 peoples opinion
Date: for any consumer product.

Aim:
To write a web services for predicting for any product sales.

Procedure:
• Open the Home page.
• View the 2 products.
• Put the rating by user.
• Display the high rating product on the top of the page.

Program:
Page.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

<head>
<title>AJAX 5 Star Rating</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
// This is the first thing we add ------------------------------------
------
$(document).ready(function () {
$('.rate_widget').each(function (i) {
var widget = this;
var out_data = {
widget_id: $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings.php',
out_data,
function (INFO) {
$(widget).data('fsr', INFO);
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
// Handles the mouseover
function () {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function () {
$(this).prevAll().andSelf().removeClass('ratings_over');
// can't use 'this' because it wont contain the updated
data
set_votes($(this).parent());
}
);
// This actually records the vote
$('.ratings_stars').bind('click', function () {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on: $(star).attr('class'),
widget_id: $(star).parent().attr('id')
};
$.post(
'ratings.php',
clicked_data,
function (INFO) {
widget.data('fsr', INFO);
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the
fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' +
avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' +
avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text(votes + ' votes recorded (' +
exact + ' rating)');
}
// END FIRST THING
</script>
<style>
.rate_widget {
border: 1px solid #CCC;
overflow: visible;
padding: 10px;
position: relative;
width: 180px;
height: 32px;
}

.ratings_stars {
background: url('star_empty.png') no-repeat;
float: left;
height: 28px;
padding: 2px;
width: 32px;
}

.ratings_vote {
background: url('star_full.png') no-repeat;
}

.ratings_over {
background: url('star_highlight.png') no-repeat;
}

.total_votes {
background: #eaeaea;
top: 58px;
left: 0;
padding: 5px;
position: absolute;
}

.movie_choice {
font: 10px verdana, sans-serif;
margin: 0 auto 40px auto;
width: 180px;
}

h1 {
text-align: center;
width: 400px;
margin: 20px auto;
}
</style>
</head>

<body>
<h1> Rate the following movies! </h1>
<div class='movie_choice'>
Rate: Raiders of the Lost Ark
<div id="r1" class="rate_widget">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
<div class='movie_choice'>
Rate: The Hunt for Red October
<div id="r2" class="rate_widget">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
</body>

</html>

Ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings
{
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid)
{
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all)
{
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
# Create a new one if it doesn't
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points']
/ $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}

Output:

Result:
Thus, the web services for predicting sales of any product have been executed successfully.

You might also like