Jump to content

I have create a page where it is suppose to render the infromation from the database accroding to the id of the selected item, Help


Go to solution Solved by kicken,

Recommended Posts

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
image.png.2e6c28f8de794ba29d76b8ed629d9784.png

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
image.png.c6485b943cacfb0081ae18d2b2bdfcda.png

 

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

image.png.deb79300d7a55d952ed2d136d7052a42.png

Edited by gula

It is a damn good idea to post REAL CODE in forums so that people can HELP you with it.  Pics of code do not make for easy help.  And use the <> icon to post the code into its own block.

4 hours ago, gula said:

I am getting this on the backend api

If you're getting a 404 then something about your server configuration is not correct.  Probably your URL rewriting configuration is incorrect.  Do you get a proper response if you try the url directly, ie: http://localhost/api/houseinfo.php?id=1

Once you've solved that issue and your script is running successfully, you can move on to fixing the JS issue (if it's still an issue at all).

 

58 minutes ago, kicken said:

If you're getting a 404 then something about your server configuration is not correct.  Probably your URL rewriting configuration is incorrect.  Do you get a proper response if you try the url directly, ie: http://localhost/api/houseinfo.php?id=1

Once you've solved that issue and your script is running successfully, you can move on to fixing the JS issue (if it's still an issue at all).

 

Yes I am getting a proper respons when I try the url directly 

 const response = await fetch(`http://localhost/api/houseinfo.php?id=1`);

image.png.8e0cd8d098fbfbe85f5abb105237d4b4.png

But what could be wrong such that when I don't send the url directly I don't get the same result

  • Solution

If you want to use /api/houseinfo/1 as your URL, then you need it have that mapped by the server to /api/houseinfo.php?id=1.  This is typically done using a URL rewriting feature of your server software. For apache, that is mod_rewrite.

Since you're getting a 404 when using /api/houseinfo/1, that implies such rewriting is not taking place.  Either you have not configured it, or have configured it incorrectly.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.