Jump to content

Error: 'id"... is not valid JSON


gula
Go to solution Solved by kicken,

Recommended Posts

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 

image.png.7ece9cf3ee86368df5f283b5fc89eeaf.png

What is the problem?

 

Link to comment
Share on other sites

  • Solution

You are not passing the ID of the record to delete in your delete request, so your script is returning the error text "Error: 'id' parameter is missing in the request."

Your Javascript code is expecting the response to be JSON data.  Your error message text is not JSON data, so trying to parse it as JSON throws an error.

Link to comment
Share on other sites

What's more, even a successful run of your endpoint doesn't return JSON. Your JS has no business attempting to read JSON from the response at all.

If you're going to do this then do it right: always return JSON, and use status codes like 400 and 500 for errors.

Link to comment
Share on other sites

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.