0% found this document useful (0 votes)
23 views

IP Assignment

The documents discuss using JSON with JavaScript, PHP, Java and Ajax. They include code examples to create and parse JSON, access JSON properties, encode PHP arrays to JSON, and make Ajax GET requests to retrieve JSON data.

Uploaded by

anurag bais
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

IP Assignment

The documents discuss using JSON with JavaScript, PHP, Java and Ajax. They include code examples to create and parse JSON, access JSON properties, encode PHP arrays to JSON, and make Ajax GET requests to retrieve JSON data.

Uploaded by

anurag bais
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Q-1.

Ajax Using Get Request


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Ajax GET Demo</title>
<script>
function displauFullName() {
var request = new XMLHttpRequest();
request.open("GET", "greet.php?fname=Om&lname=Sarvavaiya");
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
request.send();
}
</script>
</head>
<body>
<div id="result">
<p>
Content of the result DIV box will be replaced by the server response
</p>
</div>
<button type="button" onclick="displauFullName()">Display Full
Name</button>
</body>
</html>

Greet.php
<?php
if (isset($_GET["fname"]) && isset($_GET["lname"])) {
$fname = htmlspecialchars($_GET["fname"]);
$lname = htmlspecialchars($_GET["lname"]);
// Creating full name by joining first and last name
$fullname = $fname . " " . $lname;
// Displaying a welcome message
echo "Hello, $fullname!
Welcome to our website.";
} else {
echo "Hi there! Welcome to our website.";
}
?>

OUTPUT :

INITIAL PAGE :
Q-2.Ajax Using POST Request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Javascript Ajax Post Demo</title>
<script>
function postComment() {
var request = new XMLHttpRequest();

request.open("POST", "conformation.php");
request.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
var myForm = document.getElementById("myForm");
var formData = new FormData(myForm);

request.send(formData);
}
</script>
</head>
<body>
<form id="myForm">
<label>Name:</label>
<div><input type="text" name="name" /></div>
<br />
<label>Comment:</label>
<div><textarea name="comment"></textarea></div>
<p><button type="button" onclick="postComment()">Post
Comment</button></p>
</form>
<div id="result">
<p>
Content of the result DIV box will be replaced by the server response
</p>
</div>
</body>
</html>

Confirmation.php

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars(trim($_POST["name"]));
$comment = htmlspecialchars(trim($_POST["comment"]));
// Check if form fields values are empty
if (!empty($name) && !empty($comment)) {
echo "<p>Hi, <b>$name</b>. Your comment has been received
successfully.<p>";
echo "<p>Here's the comment that you've entered: <b>$comment</b></p>";
} else {
echo "<p>Please fill all the fields in the form!</p>";
}
} else {
echo "<p>Something went wrong. Please try again.</p>";
}
?>

OUTPUT:

INITIAL
Q-3. JSON with JavaScript

<html>
<head>
<title>JSON example</title>
<script language="javascript">
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };
document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied "
+ "from book
written by " + object2.author);
document.write("<hr />");
</script>
</head>
<body></body>
</html>

OUTPUT:
Q-4. JSON with PHP

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
string schemaJson = @"{ 'description': 'A person', 'type':
'object', 'properties': { 'name': {'type':'string'}, 'hobbies': { 'type':
'array', 'items': {'type':'string'} } } }"; JsonSchema schema =
JsonSchema.Parse(schemaJson); JObject person = JObject.Parse(@"{ 'name':
'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] }"); bool
valid = person.IsValid(schema); // true JSON with PHP
<?php
$arr = array('a' =>
1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

Q-5. JSON with Java

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JSON_Example7_1 {
public static void main(String[] args) {
String s="{\"name\":\"geeta\",\"salary\":600000.0,\"age\":27}";
Object obj=JSONValue.parse(s);
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
double salary = (Double) jsonObject.get("salary");
long age = (Long) jsonObject.get("age");
System.out.println(name+" "+salary+" "+age);
}
}
Q-6. JSON with Ajax
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function getWelcome() {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", "data.json");
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
//the request is completed, now check its status
if (ajaxRequest.status == 200) {
document.getElementById("welcome").innerHTML =
ajaxRequest.responseText;
} else {
console.log("Status error: " + ajaxRequest.status);
}
} else {
console.log("Ignored readyState: " + ajaxRequest.readyState);
}
};
ajaxRequest.send();
}
</script>
</head>
<body>
<button type="button" onclick="getWelcome()">Okay</button>
<p id="welcome"></p>
</body>
</html>
Q-7. A student will not be allowed to sit in exam if his/her
attendance is less than 75%.Take following input from user
Number of classes held Number of classes attended.
And print percentage of class attended Is student is allowed to
sit in exam or not. Modify the above question to allow
student to sit if he/she has medical cause. Ask user if he/she
has medical cause or not ( 'Y' or 'N' ) and print accordingly.
Write JavaScript code.

<html>
<title>Attendance</title>
<body>

<script type="text/javascript">
var n =parseInt(prompt("Enter Number Of Classes Held"));
var m =parseInt(prompt("Enter Number Of Classes Attended"));
var mr=prompt("Do You Have A Medical Cause if YES Enter Y If NO then Enter
N");

var percentage =(m*100)/n;


document.write("Your Attendance="+percentage+"%<br />");
if(percentage>=75){
document.write("<br />You Are Eligible");
}else if(mr=="Y"&&mr=="y"){
document.write("<br />You Are Eligible");

}else{
document.write("<br />You Are Not Eligible");
}

</script>

</body>
</html>
Q-8. Write JavaScript code that prompts the user to input a
positive integer. It should then print the multiplication table
of that number.

<html>
<title>input Positive Number Multiplecation table</title>
<body>
<script type="text/javascript">
var num = parseInt(prompt("Enter an integer: "));
var range = parseInt(prompt("Enter a range: "));
for (let i = 1; i <= range; i++) {
var res = i * num;
document.write(num + " * " + i + " = " + res + "<br /> ");
}
</script>
</body>
</html>
Q-9. Write a program to Check Whether the Entered Year is
Leap Year or not (Hint: A leap year is one that is divisible by
400. Otherwise, a year that is divisible by 4 but not by
100 is also a leap years. Other years are not leap years. For
example, years 1912, 2000, and 1980 are leaps years, but
1835, 1999, and 1900 are not. )
<html>
<title>Leap Year</title>
<body>
<script type="text/javascript">
var year = parseInt(prompt('Enter an integer: '));

if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {


document.write(year + ' is a leap year');
} else {
document.write(year + ' is not a leap year');
}
</script>
</body>
</html>
10. Write a JavaScript code using function without parameter
and without returning datatype type. Find the late charges
applicable for not returning the book to the library on time.
Take input as fine per day and number of days. Total fine is
the multiplication of fine per day and number of days. Find
the percentage of marks for 5 subjects. Take input as marks
for 5subjects and find the percentage.

<html>
<script>
function calculateLateCharges() {
const finePerDay = parseFloat(prompt("Enter the fine per day:"));
const numberOfDays = parseInt(prompt("Enter the number of days late:"));
const totalFine = finePerDay * numberOfDays;
document.write(
`Late charges for not returning the book on time: $${totalFine}`
);
}
function calculatePercentageOfMarks() {
let totalMarks = 0;

for (let i = 1; i <= 5; i++) {


const subjectMarks = parseFloat(
prompt(`Enter marks for subject ${i}:`)
);
totalMarks += subjectMarks;
}
const percentage = (totalMarks / 5).toFixed(2);
document.write(`Percentage of marks for 5 subjects: ${percentage}%`);
}
calculateLateCharges();
calculatePercentageOfMarks();
</script>
</html>

11. Write JavaScript code using function with parameter and


with returning datatype to implement the following
operations. Find the total salary deducted. Take input as
number of days worked, number of leaves and pay per day.
Find the total salary hike.Take input as salary and percentage
of raise received.
<!DOCTYPE html>
<html>
<head>
<title>Salary Deduction Calculator</title>
</head>
<body>
<p>
Find the total salary deducted. take input as number of days worked,
number of leaves and pay per day.
</p>

<script>
function calculateSalaryDeduction(daysWorked, leavesTaken, payPerDay) {
var totalSalary = daysWorked * payPerDay;
var deduction = leavesTaken * payPerDay;
var totalDeduction = totalSalary - deduction;
return totalDeduction;
}
var daysWorked = parseInt(prompt("Enter the number of days worked:"));
var leavesTaken = parseInt(prompt("Enter the number of leaves taken:"));
var payPerDay = parseFloat(prompt("Enter the pay per day:"));

var salaryDeduction = calculateSalaryDeduction(


daysWorked,
leavesTaken,
payPerDay
);
document.write(
"Total salary deducted: Rs. " + salaryDeduction.toFixed(2)
);
</script>
</body>
</html>
12. Create a JavaScript form for Student Registration to
capture student name, phone number and email and perform
validation using Regular Expression.
<html>
<head>
<script>
function ValidateCode() {
var name = document.forms["RegForm"]["Name"];
var email = document.forms["RegForm"]["EMail"];
var phone = document.forms["RegForm"]["Telephone"];
var what = document.forms["RegForm"]["Subject"];
var password = document.forms["RegForm"]["Password"];
var address = document.forms["RegForm"]["Address"];

if (name.value == "") {
window.alert("Please enter your name.");
name.focus();
return false;
}

if (address.value == "") {
window.alert("Please enter your address.");
address.focus();
return false;
}

if (email.value == "") {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (email.value.indexOf("@", 0) < 0) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (phone.value == "") {
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}

if (password.value == "") {
window.alert("Please enter your password");
password.focus();
return false;
}

if (what.selectedIndex < 1) {
alert("Please enter your course.");
what.focus();
return false;
}

return true;
}
</script>

<style>
ValidateCode {
margin-left: 70px;
font-weight: bold;
float: left;
clear: left;
width: 100px;
text-align: left;
margin-right: 10px;
font-family: sans-serif, bold, Arial, Helvetica;
font-size: 14px;
}

div {
box-sizing: border-box;
width: 100%;
border: 100px solid black;
float: left;
align-content: center;
align-items: center;
}

form {
margin: 0 auto;
width: 600px;
}
</style>
</head>

<body>
<h1 style="text-align: center">REGISTRATION FORM</h1>
<form
name="RegForm"
action="/submit.php"
onsubmit="return ValidateCode()"
method="post"
>
<p>Name: <input type="text" size="65" name="Name" /></p>
<br />
<p>Address: <input type="text" size="65" name="Address" /></p>
<br />
<p>E-mail Address: <input type="text" size="65" name="EMail" /></p>
<br />
<p>Password: <input type="text" size="65" name="Password" /></p>
<br />
<p>Telephone: <input type="text" size="65" name="Telephone" /></p>
<br />

<p>
SELECT YOUR COURSE
<select type="text" value="" name="Subject">
<option>BTECH</option>
<option>BBA</option>
<option>BCA</option>
<option>B.COM</option>
<option>ValidateCode</option>
</select>
</p>
<br /><br />
<p>Comments: <textarea cols="55" name="Comment"> </textarea></p>
<p>
<input type="submit" value="send" name="Submit" />
<input type="reset" value="Reset" name="Reset" />
</p>
</form>
</body>
</html>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy