0% found this document useful (0 votes)
46 views11 pages

TY IT 22 Assignment 2 WebX

This document contains an assignment for a WebX.0 course. It includes details about the assignment such as the subject, semester, year, group number, and members' names. It outlines two parts of the assignment: 1) Designing and developing a small web application using AJAX, HTML, and PHP that allows users to submit feedback via a form. 2) Building a REST API using MongoDB and Flask to store and retrieve data from a database. Code snippets are provided for each part, including HTML, CSS, JavaScript, PHP, and Python code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views11 pages

TY IT 22 Assignment 2 WebX

This document contains an assignment for a WebX.0 course. It includes details about the assignment such as the subject, semester, year, group number, and members' names. It outlines two parts of the assignment: 1) Designing and developing a small web application using AJAX, HTML, and PHP that allows users to submit feedback via a form. 2) Building a REST API using MongoDB and Flask to store and retrieve data from a database. Code snippets are provided for each part, including HTML, CSS, JavaScript, PHP, and Python code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

WebX.

0 Assignment-2

Subject name – WebX.0

Semester – 6

Year:2022-23

Group no- 8

Members name:-

Sanjay Jogi (21)

Mansoor Kanorewala (22)

Musaveer Manekia (23)

Abbas Najmi (24)

Part A:
1. Design and develop small web applications using AJAX, HTML and PHP. Code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}
h2 {
margin-top: 50px;
text-align: center;
color: #333;
}
form {
max-width: 500px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
border-radius: 5px;
}
label {
display: block;
font-size: 16px;
font-weight: bold;
margin-bottom: 5px;
color: #333;
}
input[type="text"], input[type="email"], textarea { display: block;
width: 100%;
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
border: none;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
font-size: 16px;
}
textarea {
height: 100px;
resize: none;
}
button[type="submit"] {
background-color: #333;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
#feedback-message {
max-width: 500px;
margin: 20px auto;
background-color: #e6ffe6;
padding: 20px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
border-radius: 5px;
color: #333;
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script
src="script.js"></script>
</head>
<body>
<h2>Feedback Form</h2>
<form id="feedback-form" onsubmit="return false;"> <label
for="name">Name:</label>
<input type="text" name="name" required>
<label for="email">Email:</label>
<input type="email" name="email" required>
<label for="message">Message:</label>
<textarea name="message" required></textarea>
<button type="submit" onclick="showSuccess()">Submit</button>
</form>
<div id="feedback-message"></div>
<script>
function showSuccess() {
document.getElementById("feedback-message").innerHTML = "Feedback
successfully submitted!";
document.getElementById("feedback-message").style.display = "block";
document.getElementById("feedback-form").reset();
}
</script>
</body>
</html>
PHP:
<?php
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Validate form data


if (empty($name) || empty($email) || empty($message)) { $response =
array('success' => false);
echo json_encode($response);
exit;
}

// Insert form data into database (replace with your own database connection code) $servername =
"localhost";
$username = "username";
$password = "password";
$dbname = "my
Ajax:
$(document).ready(function() {
$('#feedback-form').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'submit-feedback.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
if (data.success) {
$('#feedback
message').removeClass('error').addClass('success').text('Thank you for your feedback!');
$('#feedback-form')[0].reset();
} else {
$('#feedback
message').removeClass('success').addClass('error').text('Sorry, an error occurred. Please try again
later.');
}
})
.fail(function() {
$('#feedback
message').removeClass('success').addClass('error').text('Sorry, an error occurred. Please try again
later.');
});
});
});

2: Build a REST API using MongoDB and Flask.


Building a REST API using MongoDB and Flask involves combining the Flask framework, which is a
popular web framework for Python, with MongoDB, which is a NoSQL database. The Flask framework
provides a lightweight and flexible approach to building web applications, while MongoDB provides a highly
scalable and flexible data storage solution. To build a REST API with Flask and MongoDB, you would
typically start by creating a Flask application, defining endpoints for different HTTP methods such as GET,
POST, PUT, and DELETE, and then integrating with MongoDB to store and retrieve data. Some key steps in
building a Flask and MongoDB REST API might include:
1. Creating a virtual environment for your Flask application 2. Installing Flask and
other necessary dependencies
3. Creating a Flask app and defining routes for various endpoints 4. Connecting to a MongoDB database
using PyMongo or similar library 5. Defining models for your data and creating schemas for MongoDB
collections 6. Implementing CRUD operations (Create, Read, Update, Delete) for your data
7. Securing your API using authentication and authorization mechanisms Overall, building a REST API
using MongoDB and Flask can be a powerful way to create highly scalable and flexible web applications. By
combining the strengths of both Flask and MongoDB, developers can create fast, efficient, and reliable APIs
that can handle large volumes of data and provide a high level of performance and flexibility.

Outputs:-
import os
import sqlite3

from flask import Flask, jsonify, make_response, redirect, render_template, request, session, url_for

import settings

app = Flask(__name__)
app.config.from_object(settings)

# Helper functions
def _get_message(id=None):
"""Return a list of message objects (as dicts)"""
with sqlite3.connect(app.config['DATABASE']) as conn:
c = conn.cursor()

if id:
id = int(id) # Ensure that we have a valid id value to query q = "SELECT * FROM messages
WHERE id=? ORDER BY dt DESC" rows = c.execute(q, (id,))

else:
q = "SELECT * FROM messages ORDER BY dt DESC" rows = c.execute(q)
return [{'id': r[0], 'dt': r[1], 'message': r[2], 'sender': r[3]} for r in rows]
def _add_message(message, sender):
with sqlite3.connect(app.config['DATABASE']) as conn: c =
conn.cursor()
q = "INSERT INTO messages VALUES (NULL, datetime('now'),?,?)" c.execute(q, (message,
sender))
conn.commit()
return c.lastrowid

def _delete_message(ids):
with sqlite3.connect(app.config['DATABASE']) as conn: c =
conn.cursor()
q = "DELETE FROM messages WHERE id=?"

# Try/catch in case 'ids' isn't an iterable


try:
for i in ids:
c.execute(q, (int(i),))
except TypeError:
c.execute(q, (int(ids),))

conn.commit()

# Standard routing (server-side rendered pages)


@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
_add_message(request.form['message'], request.form['username'])
redirect(url_for('home'))

return render_template('index.html', messages=_get_message())

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/admin', methods=['GET', 'POST'])


def admin():
if not 'logged_in' in session:
return redirect(url_for('login'))

if request.method == 'POST':
# This little hack is needed for testing due to how Python dictionary keys work _delete_message([k[6:] for k in
request.form.keys()])
redirect(url_for('admin'))

messages = _get_message()
messages.reverse()

return render_template('admin.html', messages=messages)

@app.route('/login', methods=['GET', 'POST'])


def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME'] or request.form['password'] !=
app.config['PASSWORD']:
error = 'Invalid username and/or password'
else:
session['logged_in'] = True
return redirect(url_for('admin'))
return render_template('login.html', error=error)

@app.route('/logout')
def logout():
session.pop('logged_in', None)
return redirect(url_for('home'))
# RESTful routing (serves JSON to provide an external API)
@app.route('/messages/api', methods=['GET'])
@app.route('/messages/api/<int:id>', methods=['GET'])
def get_message_by_id(id=None):
messages = _get_message(id)
if not messages:
return make_response(jsonify({'error': 'Not found'}), 404) return

jsonify({'messages': messages})

@app.route('/messages/api', methods=['POST'])
def create_message():
if not request.json or not 'message' in request.json or not 'sender' in request.json: return
make_response(jsonify({'error': 'Bad request'}), 400)

id = _add_message(request.json['message'], request.json['sender']) return

get_message_by_id(id), 201

@app.route('/messages/api/<int:id>', methods=['DELETE']) def


delete_message_by_id(id):
_delete_message(id)
return jsonify({'result': True})

if __name__ == '__main__':

# Test whether the database exists; if not, create it and create the table if not
os.path.exists(app.config['DATABASE']):
try:
conn = sqlite3.connect(app.config['DATABASE'])

# Absolute path needed for testing environment


sql_path = os.path.join(app.config['APP_ROOT'], 'db_init.sql') cmd = open(sql_path,
'r').read()
c = conn.cursor()
c.execute(cmd)
conn.commit()
conn.close()
except IOError:
print("Couldn't initialize the database, exiting...") raise
except sqlite3.OperationalError:
print("Couldn't execute the SQL, exiting...")
raise

app.run()

You might also like