Jump to content

gula

Members
  • Posts

    10
  • Joined

  • Last visited

gula's Achievements

Member

Member (2/5)

0

Reputation

  1. Yes I am getting a proper respons when I try the url directly const response = await fetch(`http://localhost/api/houseinfo.php?id=1`); But what could be wrong such that when I don't send the url directly I don't get the same result
  2. I am creating a real estate management system and I have run into this problem and I have run out of ideas of how to get this things render the info of the house as I intend it to. This page is rendered by listings.js the code of this page is below This is the page where when i click on a house it shoud take me to the next page and renders its info from the database accroding to its corresponding id But I am not getting the info of the house on the next page this is what I am getting on the console I am writing the frontend in reactjs This is listings.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Link } from 'react-router-dom'; import './css/Listings.css'; const Listings = () => { const [houses, setHouses] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [searchTerm, setSearchTerm] = useState(''); // State for search term useEffect(() => { const fetchHouses = async () => { try { const response = await axios.get('http://localhost/api/listings.php'); setHouses(response.data); } catch (error) { console.error('Error fetching houses:', error); } }; fetchHouses(); }, []); const handleNextPage = () => { setCurrentPage(currentPage + 1); }; const handlePrevPage = () => { setCurrentPage(currentPage - 1); }; const startIndex = (currentPage - 1) * 6; const endIndex = startIndex + 6; const handleHouseClick = (id) => { console.log(`House ID: ${id}`); axios .post(`http://localhost:80/api/houseinfo.php?id=${id}`) .then((response) => { console.log('Response:', response.data); }) .catch((error) => { console.error('Error:', error); }); }; const handleSearchTermChange = (event) => { setSearchTerm(event.target.value); }; // Function to handle form submission const handleSubmit = (event) => { event.preventDefault(); console.log('Search Term:', searchTerm); }; return ( <div className="listings-container"> <form className="search-form" onSubmit={handleSubmit}> <input type="text" className="search-input" placeholder="Search by title, location, or type" value={searchTerm} onChange={handleSearchTermChange} /> <button type="submit" className="search-button"> Search </button> </form> <div className="house-grid"> {houses .filter( (house) => house.title.toLowerCase().includes(searchTerm.toLowerCase()) || house.location.toLowerCase().includes(searchTerm.toLowerCase()) || house.type.toLowerCase().includes(searchTerm.toLowerCase()) ) .slice(startIndex, endIndex) .map((house, index) => ( <div key={index} className="house-card"> <Link to={`/houseinfo/${house.id}`} className="house-card-content" onClick={() => handleHouseClick(house.id)} // Pass house id to handleHouseClick > <img src={house.image1} alt={house.title} className="house-image" /> <h2 className="house-title">{house.title}</h2> </Link> </div> ))} </div> <div className="pagination"> {currentPage > 1 && ( <button className="pagination-button" onClick={handlePrevPage}> {'<'} </button> )} <span className="pagination-page">{currentPage}</span> {endIndex < houses.length && ( <button className="pagination-button" onClick={handleNextPage}> {'>'} </button> )} </div> </div> ); }; export default Listings; This is the houseinfo.js import React, { useState, useEffect } from 'react'; import { useParams } from 'react-router' const HouseInfo = ({ match }) => { const [listings, setListings] = useState(null); const {id} = useParams(); useEffect(() => { // Fetch house data from API based on house ID const fetchListings = async () => { try { const response = await fetch(`http://localhost:80/api/houseinfo/${id}`); const data = await response.json(); setListings(data); } catch (error) { console.error('Error fetching house:', error); } }; fetchListings(); }, [id]); if (!listings) { return <div>Loading...</div>; } return ( <div> <h1>House Information</h1> <ul> <li>Title: {listings.title}</li> <li>Location: {listings.location}</li> <li>Price: {listings.price}</li> </ul> </div> ); }; export default HouseInfo; And I am writing backend in php This is houseinfo.php <?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET'); header('Access-Control-Allow-Headers: Content-Type'); $conn = mysqli_connect('localhost', 'root', '', 'realestate1'); if (!$conn) { die('Failed to connect to MySQL: ' . mysqli_connect_error()); } $houseId = $_GET['id']; $query = "SELECT * FROM listings WHERE id = ?"; $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, 'i', $houseId); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$result) { die('Failed to fetch house data: ' . mysqli_error($conn)); } if (mysqli_num_rows($result) == 0) { die('House not found'); } $house = mysqli_fetch_assoc($result); $houseJson = json_encode($house); echo $houseJson; mysqli_stmt_close($stmt); mysqli_close($conn); ?> I am getting this on the backend api
  3. By something is wrong by I mean it is not woring at intended, the console is priniting login successful even though I enter wrong email and password
  4. I have made a login page using reactjs as my frontend, php as my backend and mysql as my database but there seems to be something wrong that I can't seem to figure it out so please help This is my frontend import React, { useState } from 'react'; import './css/Login.css'; import { Link } from 'react-router-dom'; function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const handleEmailChange = (event) => { setEmail(event.target.value); }; const handlePasswordChange = (event) => { setPassword(event.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); try { // Make an API call to your backend service or database to validate the email and password const response = await fetch('http://localhost:80/api/login.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password }), }); // Handle the response and perform appropriate actions if (response.ok) { // If response is successful, perform login action // e.g. redirect to dashboard or set authentication state console.log('Login successful'); } else { // If response is not successful, display error message setError('Invalid email or password'); } } catch (error) { // Handle any errors that may occur during the API call console.error('Login error:', error); setError('Failed to login. Please try again later.'); } }; return ( <div className="login-container"> <h1 className="login-heading">Login</h1> <form onSubmit={handleSubmit} className="login-form"> <div> <label htmlFor="email" className="login-label"></label> <input type="email" placeholder='Email' id="email" value={email} onChange={handleEmailChange} className="login-form-input" /> </div> <div> <label htmlFor="password" className="login-label"></label> <input type="password" placeholder='Password' id="password" value={password} onChange={handlePasswordChange} className="login-form-input" /> </div> <button type="submit" className="login-button">Login</button> {error && <p className="login-error">{error}</p>} <p className="login-text">New to?</p><Link to="/Register" className="login-link">Register</Link> </form> </div> ); } export default Login; This is my backend <?php header('Access-Control-Allow-Origin: http://localhost:3000'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Requested-With, Accept'); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = json_decode(file_get_contents('php://input'), true); $email = $data['email']; $password = $data['password']; $conn = mysqli_connect('localhost', 'root', '', 'realestate1'); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $query = "SELECT * FROM `registration` WHERE `email` = ?"; $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, "s", $email); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); $storedPassword = $row['password']; if (password_verify($password, $storedPassword)) { http_response_code(200); echo json_encode(['message' => 'Login successful']); } else { echo json_encode(['error' => 'Invalid email or password']); } } else { echo json_encode(['error' => 'Invalid email or password']); } mysqli_stmt_close($stmt); mysqli_close($conn); } else { http_response_code(400); echo json_encode(['error' => 'Bad Request']); } ?> This is my database table
  5. I have a delete button that is not working when I click on it it is showing me that error in the console I am using react for my front-end, php for my backend and mysql for my database This is the frontend code import React, { useEffect, useState } from "react"; import "./user.css"; const Buy = () => { const [buyData, setBuyData] = useState([]); const [formData, setFormData] = useState({ id: "", name: "", purpose: "", type: "", area: "", price: "", location: "", status: "", }); const [showForm, setShowForm] = useState(false); // Added state to control form visibility useEffect(() => { fetchBuyData(); }, []); const fetchBuyData = async () => { try { const response = await fetch("http://localhost:80/api/buy.php"); const data = await response.json(); setBuyData(data); } catch (error) { console.error("Error fetching buy data:", error); } }; const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; const handleFormSubmit = async (e) => { e.preventDefault(); try { const response = await fetch(`http://localhost:80/api/buy.php`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData), }); const data = await response.json(); console.log("Data updated successfully:", data); fetchBuyData(); } catch (error) { console.error("Error updating buy data:", error); } }; const handleDeleteClick = async (id) => { try { const response = await fetch( `http://localhost:80/api/buydelete.php?id= `, { method: "DELETE" } ); const data = await response.json(); console.log("Data deleted successfully:", data); fetchBuyData(); } catch (error) { console.error("Error deleting buy data:", error); } }; const handleUpdateClick = (item) => { setFormData({ id: item.id, name: item.name, purpose: item.purpose, type: item.type, area: item.area, price: item.price, location: item.location, status: item.status, }); setShowForm(true); // Show form when update button is clicked }; return ( <div> <h1>Buy Page</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Purpose</th> <th>Type</th> <th>Area</th> <th>Price</th> <th>Location</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody> {buyData.map((item) => ( <tr key={item.id}> <td>{item.id}</td> <td>{item.name}</td> <td>{item.purpose}</td> <td>{item.type}</td> <td>{item.area}</td> <td>{item.price}</td> <td>{item.location}</td> <td>{item.status}</td> <td> <button onClick={() => handleUpdateClick(item)}>Update</button> <button onClick={() => handleDeleteClick(item.id)}> Delete </button> </td> </tr> ))} </tbody> </table> {/* Form for updating data */} {showForm && ( <form onSubmit={handleFormSubmit}> <h2>Update Data</h2> <label htmlFor="name">Name</label> <input type="text" name="name" value={formData.name} onChange={handleInputChange} /> <label htmlFor="name">Purpose</label> <input type="text" name="purpose" value={formData.purpose} onChange={handleInputChange} /> <label htmlFor="type">Type</label> <input type="text" name="type" value={formData.type} onChange={handleInputChange} /> <label htmlFor="area">Area</label> <input type="text" name="area" value={formData.area} onChange={handleInputChange} /> <label htmlFor="price">Price</label> <input type="text" name="price" value={formData.price} onChange={handleInputChange} /> <label htmlFor="location">Location</label> <input type="text" name="location" value={formData.location} onChange={handleInputChange} /> <label htmlFor="status">Status</label> <input type="text" name="status" value={formData.status} onChange={handleInputChange} /> <button type="submit">Submit</button> </form> )} </div> ); }; export default Buy; And this is the back-end code <?php header('Access-Control-Allow-Origin: http://localhost:3000'); header('Access-Control-Allow-Methods: DELETE'); header('Access-Control-Allow-Headers: Content-Type'); if(isset($_POST['id'])) { $id = $_POST['id']; $conn = new mysqli('localhost', 'root', '', 'realestate1'); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $stmt = $conn->prepare("DELETE FROM property-buy WHERE id = $id"); $stmt->bind_param("i", $id); if ($stmt->execute()) { echo "Data deleted successfully"; } else { echo "Error deleting data: " . $stmt->error; } $stmt->close(); $conn->close(); } else { echo "Error: 'id' parameter is missing in the request."; } ?> And this is my database What is the problem?
  6. <?php include("connection.php"); // Check if the form is submitted if (isset($_POST['submit'])) { // Retrieve the user's information from the form $Bus_id =$_POST['Bus_id']; $city = $_POST['city']; $Destination = $_POST['Destination']; $bus_number = $_POST['Bus_number']; $departure_date = $_POST['departure_date']; $departure_time = $_POST['departure_time']; $cost = $_POST['cost']; $seat_id = $_POST['seat_id']; $fullName = $_POST['fullName']; $contactNumber = $_POST['contactNumber']; $email = $_POST['email']; $gender = $_POST['gender']; // Prepare and execute the sql query to insert the user's information into the "bookings" table $stmt = mysqli_prepare($conn, "INSERT INTO `bookings` (Bus_id, city, Destination, Bus_number, departure_date, departure_time, cost, seat_id, fullName, contactNumber, email, gender) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); // Bind the variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ssssssssssss", $bus_id, $city, $destination, $bus_number, $departure_date, $departure_time, $cost, $seat_id, $fullName, $contactNumber, $email, $gender); if (mysqli_stmt_execute($stmt)) { echo "Booking Successful!"; } else { echo "Booking Failed!"; } // Close the database connection mysqli_close($conn); } if (isset($_POST['seat_id'])) { $seatId = $_POST['seat_id']; // Check if the seat is available $query = "SELECT * FROM seats WHERE seat_id = '$seatId' AND is_booked = 0"; $result = mysqli_query($conn, $query); if (mysqli_num_rows($result) > 0) { // Book the seat $query = "UPDATE seats SET is_booked = 1 WHERE seat_id = '$seatId'"; mysqli_query($conn, $query); $message = 'Seat booked successfully'; } else { echo 'Seat is already booked'; } } ?>
  7. I have created a the frontend fo the registration page in react and wrote backend in php and I have used mysql as my database This is my frontend code import React, { useState } from "react"; import "./css/Register.css"; import { Link } from "react-router-dom"; import axios from "axios"; function Register() { const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const [mobileNumber, setMobileNumber] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [validationErrors, setValidationErrors] = useState({ emailError: "", mobileNumberError: "", passwordMatchError: "", }); const handleSubmit = (e) => { e.preventDefault(); // Email validation using regular expression const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; let newErrors = { emailError: "", mobileNumberError: "", passwordMatchError: "", }; if (!emailPattern.test(email)) { newErrors.emailError = "Please enter a valid email address"; } if (mobileNumber.length !== 10) { newErrors.mobileNumberError = "Please enter a valid mobile number"; } if (password !== confirmPassword) { newErrors.passwordMatchError = "Passwords do not match"; } if ( newErrors.emailError || newErrors.mobileNumberError || newErrors.passwordMatchError ) { setValidationErrors(newErrors); } else { setValidationErrors({ emailError: "", mobileNumberError: "", passwordMatchError: "", }); const userData = { firstName: firstName, lastName: lastName, email: email, mobileNumber: mobileNumber, password: password, }; axios.post("http://localhost:80/api/registration.php", userData); console.log(`UserData: ${JSON.stringify(userData)}`); } }; return ( <div className="register-container"> <h1 className="register-heading">Register</h1> <form onSubmit={handleSubmit} className="register-form"> <label className="register-label"> <input type="text" placeholder="First Name" value={firstName} onChange={(e) => setFirstName(e.target.value)} className="register-input" required /> </label> <br /> <label className="register-label"> <input type="text" placeholder="Last Name" value={lastName} onChange={(e) => setLastName(e.target.value)} className="register-input" required /> </label> <br /> <label className="register-label"> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} className="register-input" required /> </label> {validationErrors.emailError && ( <p className="register-error">{validationErrors.emailError}</p> )} <br /> <label className="register-label"> <input type="tel" placeholder="Mobile Number" value={mobileNumber} onChange={(e) => setMobileNumber(e.target.value)} className="register-input" required /> </label> {validationErrors.mobileNumberError && ( <p className="register-error">{validationErrors.mobileNumberError}</p> )} <br /> <label className="register-label"> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} className="register-input" required /> </label> <br /> <label className="register-label"> <input type="password" placeholder="Confirm Password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} className="register-input" required /> </label> {validationErrors.passwordMatchError && ( <p className="register-error"> {validationErrors.passwordMatchError} </p> )} <br /> <button type="submit" className="register-button"> Register </button> </form> <p className="register-login-link"> Already have an account? <Link to="/login">Login</Link> </p> </div> ); } export default Register; and this is my backend <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "realestate"; header('Access-Control-Allow-Origin: http://localhost:3000'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type'); $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $data = json_decode(file_get_contents('php://input'), true); if (isset($data['name']) && isset($data['email']) && isset($data['mobileNumber']) && isset($data['password'])) { $name = $data['name']; $email = $data['email']; $mobileNumber = $data['mobileNumber']; $password = $data['password']; $stmt = mysqli_prepare($conn, "INSERT INTO `registration` (`name`,`email`,`mobileNumber`,`Password`) VALUES (?, ?, ?, ?)"); mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $mobileNumber, $password); if (mysqli_stmt_execute($stmt)) { $response = array('status' => 'success', 'message' => 'Data stored successfully!'); } else { $response = array('status' => 'error', 'message' => 'Error: ' . mysqli_error($conn)); } mysqli_stmt_close($stmt); mysqli_close($conn); header('Content-Type: application/json'); echo json_encode($response); } ?> This is the screenshot of the table in database What is the error in the code that I have not been able to find please help me because no data is getting inserted in the database please help
  8. <?php include("connection.php"); // Check if the form is submitted if (isset($_POST['submit'])) { // Retrieve the user's information from the form $bus_id =$_POST['Bus_id']; $city = $_POST['city']; $destination = $_POST['Destination']; $bus_number = $_POST['Bus_number']; $departure_date = $_POST['departure_date']; $departure_time = $_POST['departure_time']; $cost = $_POST['cost']; $seat_id = $_POST['seat_id']; $fullName = $_POST['fullName']; $contactNumber = $_POST['contactNumber']; $email = $_POST['email']; $gender = $_POST['gender']; // Check if the connection is successful if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Prepare and execute the sql query to insert the user's information into the "booking" table $stmt = mysqli_prepare($conn, "INSERT INTO booking (bus_id, city, destination, bus_number, departure_date, departure_time, cost, seat_id, full_name, contact_number, email, gender) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); // Bind the variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ssssssssssss", $bus_id, $city, $destination, $bus_number, $departure_date, $departure_time, $cost, $seat_id, $fullName, $contactNumber, $email, $gender); if (mysqli_stmt_execute($stmt)) { echo "Booking Successful!"; } else { echo "Booking Failed!"; } // Close the database connection mysqli_close($conn); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>booking</title> <link rel="stylesheet" href="css/booking.css"> </head> <body> <h1>Seat Booking</h1> <div class="bus-layout"> <table class="seating-layout"> <tbody> <tr> <td> <a class="seat" data-seat="B2">B2</a> </td> <td> <a class="seat" data-seat="B4">B4</a> </td> <td> <a class="seat" data-seat="B6">B6</a> </td> <td> <a class="seat" data-seat="B8">B8</a> </td> <td> <a class="seat" data-seat="B10">B10</a> </td> <td> <a class="seat" data-seat="B12">B12</a> </td> <td> <a class="seat" data-seat="B14">B14</a> </td> <td> <a class="seat" data-seat="B16">B16</a> </td> <td> <a class="seat" data-seat="B18">B18</a> </td> </tr> <tr> <td> <a class="seat" data-seat="B1">B1</a> </td> <td> <a class="seat" data-seat="B3">B3</a> </td> <td> <a class="seat" data-seat="B5">B5</a> </td> <td> <a class="seat" data-seat="B7">B7</a> </td> <td> <a class="seat" data-seat="B9">B9</a> </td> <td> <a class="seat" data-seat="B11">B11</a> </td> <td> <a class="seat" data-seat="B13">B13</a> </td> <td> <a class="seat" data-seat="B15">B15</a> </td> <td> <a class="seat" data-seat="B17">B17</a> </td> </tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td> <a class="seat" data-seat="A17">A17</a> </td> <tr> <td> </td> <td> <a class="seat" data-seat="A2">A2</a> </td> <td> <a class="seat" data-seat="A4">A4</a> </td> <td> <a class="seat" data-seat="A6">A6</a> </td> <td> <a class="seat" data-seat="A8">A8</a> </td> <td> <a class="seat" data-seat="A10">A10</a> </td> <td> <a class="seat" data-seat="A12">A12</a> </td> <td> <a class="seat" data-seat="A14">A14</a> </td> <td> <a class="seat" data-seat="A16">A16</a> </td> </tr> <tr> <td> </td> <td> <a class="seat" data-seat="A1">A1</a> </td> <td> <a class="seat" data-seat="A3">A3</a> </td> <td> <a class="seat" data-seat="A5">A5</a> </td> <td> <a class="seat" data-seat="A7">A7</a> </td> <td> <a class="seat" data-seat="A9">A9</a> </td> <td> <a class="seat" data-seat="A11">A11</a> </td> <td> <a class="seat" data-seat="A13">A13</a> </td> <td> <a class="seat" data-seat="A15">A15</a> </td> </tr> </tbody> </table> </div> <div class="form-container"> <form method="POST"> <h3>Passenger Information</h3> <input type="hidden" name="Bus_id" value="<?php echo $_GET['Bus_id']; ?>"> <input type="hidden" name="city" value="<?php echo $_GET['city']; ?>"> <input type="hidden" name="Destination" value="<?php echo $_GET['Destination']; ?>"> <input type="hidden" name="Bus_number" value="<?php echo $_GET['Bus_number']; ?>"> <input type="hidden" name="departure_date" value="<?php echo $_GET['departure_date']; ?>"> <input type="hidden" name="departure_time" value="<?php echo $_GET['departure_time']; ?>"> <input type="hidden" name="cost" value="<?php echo $_GET['cost']; ?>"> <label for="seat_id">seat Id:</label> <input type="text" id="seat_id" name="seat_id" value=""> <br> <label for="fullName">Full Name:</label> <input type="text" id="fullName" name="fullName" required> <br> <label for="contactNumber">Contact Number:</label> <input type="tel" id="contactNumber" name="contactNumber" required> <br> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <br> <label for="gender">Gender:</label> <select id="gender" name="gender" required> <option value="">Select Gender</option> <option value="male">Male</option> <option value="female">Female</option> <option value="other">Other</option> </select> <br> <button id="book-btn" class="login" type="submit" name="submit">Book</button> </form> </div> <script> // Get all seat elements on the page var seatElements = document.querySelectorAll('.seat'); // Add a click event listener to each seat element seatElements.forEach(function(seatElement) { seatElement.addEventListener('click', function(event) { // Get the seat ID from the data-seat attribute var seatId = event.target.getAttribute('data-seat'); // Use the bus ID and seat ID to check seat availability on the server // ... // Create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // Define the callback function to handle the response xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // Handle the response from the server var availability = xhr.responseText; console.log('Seat availability:', availability); // Change the color of the seat based on availability if (availability === 'unavailable') { seatElement.style.backgroundColor = 'red'; } else { seatElement.style.backgroundColor = 'yellow'; } } }; // Get the bus ID from PHP var busId = <?php echo json_encode($bus_id); ?>; // Open the XMLHttpRequest with the GET method and the URL for the server endpoint xhr.open('GET', `check_seat_availability.php?bus_id=${busId}&seat_id=${seatId}`, true); // Send the XMLHttpRequest xhr.send(); }); }); </script> </body> </html>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.