0% found this document useful (0 votes)
10 views14 pages

Web Guess

The document provides a comprehensive overview of various programming concepts in JavaScript, PHP, databases, and Laravel, including form validation, AJAX, database connections, and MVC architecture. It includes code examples for each topic to illustrate their usage, such as email validation, data handling with POST and GET methods, and basic syntax for functions and loops. Additionally, it covers practical applications like uploading files, session management, and calculating sums using both PHP and JavaScript.

Uploaded by

M Numan Zafar
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)
10 views14 pages

Web Guess

The document provides a comprehensive overview of various programming concepts in JavaScript, PHP, databases, and Laravel, including form validation, AJAX, database connections, and MVC architecture. It includes code examples for each topic to illustrate their usage, such as email validation, data handling with POST and GET methods, and basic syntax for functions and loops. Additionally, it covers practical applications like uploading files, session management, and calculating sums using both PHP and JavaScript.

Uploaded by

M Numan Zafar
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/ 14

Here’s an explanation and examples of each topic you asked for in

simple words:

JavaScript
1. Form Validation
• Validation checks if a form has been correctly filled
before submission.

<form id="myForm">
<input type="text" id="name" placeholder="Name"
required>
<button type="submit">Submit</button>
</form>

<script>

document.getElementById("myForm").addEventListener("subm
it", function(event) {
let name = document.getElementById("name").value;
if (name === "") {
alert("Name cannot be empty!");
event.preventDefault(); // Prevent form submission
}
});
</script>
2. AJAX (Asynchronous JavaScript and XML)
• It allows updating parts of a web page without
reloading the whole page.

const xhr = new XMLHttpRequest();


xhr.open("GET", "data.php", true);
xhr.onload = function() {
if (this.status === 200) {
console.log(this.responseText); // Displays response from
server
}
};
xhr.send();

3. Get/Set Element Text/Value


• Get Value:

let inputValue = document.getElementById("name").value;


console.log(inputValue);

• Set Value:

document.getElementById("name").value = "John Doe";


4. Basic Function and Variable

let name = "John"; // Variable


function greet() { // Function
console.log("Hello, " + name + "!");
}
greet();

PHP
1. Database Connection

$conn = new mysqli("localhost", "root", "", "my_database");


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected!";

2. isset()
• Checks if a variable is set and not null.

if (isset($_POST['submit'])) {
echo "Form submitted!";
}

3. $_POST and $_GET


• $_POST: Retrieves form data sent via POST method.
• $_GET: Retrieves data sent via URL parameters.

// POST Example
if (isset($_POST['name'])) {
echo "Name: " . $_POST['name'];
}

// GET Example
if (isset($_GET['id'])) {
echo "ID: " . $_GET['id'];
}

4. Upload Documents to Server

if (isset($_FILES['file'])) {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["file"]
["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"],
$targetFile)) {
echo "File uploaded successfully!";
} else {
echo "File upload failed.";
}
}

5. Basic Syntax: If/Else, Function, Loop

// If/Else
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are underage.";
}

// Function
function greet($name) {
return "Hello, $name!";
}
echo greet("John");
// Loop
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}

6. Sessions and Cookies

// Session
session_start();
$_SESSION['username'] = "John";
echo "Session set: " . $_SESSION['username'];

// Cookie
setcookie("user", "John", time() + 3600, "/");
echo "Cookie set: " . $_COOKIE['user'];

Database
1. Basic Queries

-- Insert
INSERT INTO users (name, email) VALUES ('John',
'[email protected]');

-- Select
SELECT * FROM users;

-- Delete
DELETE FROM users WHERE id = 1;

Laravel
1. MVC (Model-View-Controller)
• Model: Interacts with the database.
• View: Displays data to users (HTML).
• Controller: Handles user requests and communicates
with models and views.
2. View
• Stores HTML templates in the resources/views
directory.

// Return a view
return view('welcome');

3. Routes
• Define URL paths and associate them with logic in the
routes/web.php file.

Route::get('/', function () {
return view('welcome');
});
4. Controller
• Handles requests and returns responses. Controllers
are stored in the app/Http/Controllers directory.

// Generate a controller
php artisan make:controller UserController

// Example function
public function show($id) {
return "User ID: " . $id;
}

5. Sending Data via Controller

public function show() {


$data = ['name' => 'John', 'email' => '[email protected]'];
return view('profile', compact('data'));
}

Let me know if you need further details!


Here’s the explanation and code for each topic:
1. PHP Email Validation

You can validate an email using PHP’s built-in filter_var()


function.

<?php
if (isset($_POST['submit'])) {
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email: $email";
} else {
echo "Invalid email address.";
}
}
?>
<form method="post">
<input type="text" name="email" placeholder="Enter your
email">
<button type="submit" name="submit">Validate</button>
</form>

2. PHP Form Validation

Form validation ensures all required fields are filled out


correctly.
<?php
$nameErr = $emailErr = "";
$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = $_POST["name"];
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} elseif (!filter_var($_POST["email"],
FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$email = $_POST["email"];
}
}
?>
<form method="post">
Name: <input type="text" name="name">
<span><?php echo $nameErr; ?></span><br>
Email: <input type="text" name="email">
<span><?php echo $emailErr; ?></span><br>
<button type="submit">Submit</button>
</form>

3. PHP Database Connection in a Form

Below is an example of connecting a form to a MySQL database


and storing user input.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";

// Create connection
$conn = new mysqli($servername, $username, $password,
$database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name',
'$email')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $conn->error;
}
}
?>
<form method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<button type="submit">Submit</button>
</form>

4. PHP: Take Two Numbers and Show Their Sum

PHP Code:

<?php
if (isset($_POST['submit'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$sum = $num1 + $num2;
echo "Sum: $sum";
}
?>
<form method="post">
Number 1: <input type="number" name="num1"><br>
Number 2: <input type="number" name="num2"><br>
<button type="submit" name="submit">Calculate</button>
</form>

5. JavaScript: Take Two Numbers and Show Their Sum

HTML and JS Code:

<form id="sumForm">
Number 1: <input type="number" id="num1"><br>
Number 2: <input type="number" id="num2"><br>
<button type="button"
onclick="calculateSum()">Calculate</button>
</form>
<p id="result"></p>

<script>
function calculateSum() {
let num1 =
parseFloat(document.getElementById('num1').value);
let num2 =
parseFloat(document.getElementById('num2').value);
let sum = num1 + num2;
document.getElementById('result').innerText = "Sum: " +
sum;
}
</script>

Let me know if you need further clarification or assistance!

You might also like