skip to Main Content

hi I would like to solve this problem, in my react app I have to receive the json data taken from an index.php, testing only the php gives me the json data correctly, while the react app tells me that they are not in the right format
your textI need to make an app that returns an ag-grid table containing the data taken from my company’s Apache server
next there is my app.js file where i wrote my code

import './App.css';
import { AgGridReact } from 'ag-grid-react';

import {useState, useEffect, useMemo} from 'react';

import 'ag-grid-community/styles/ag-grid.css'; 
import 'ag-grid-community/styles/ag-theme-alpine.css';

function App() {
 //dichiarazione tabella
 //example data
 const [rowData, setRowData] = useState([
  {id: 'Ford', nome: 'Focus', cognome: 400000},
  {id: 'BMW', nome: '3 Series', cognome: 52641},
  {id: 'Audi', nome: 'A8L', cognome: 79147},
 ]);
 
 const [columnDefs,_setColumnDefs] = useState([
                { headerName: 'ID', field: 'COL 1' },
                { headerName: 'NOME', field: 'COL 2' },
                { headerName: 'COGNOME', field: 'COL 3' },
                { headerName: 'MACCHINA', field: 'COL 4' },
                { headerName: 'GIORNO', field: 'COL 5' },
                { headerName: 'LAVORO', field: 'COL 6' },
                { headerName: 'INIZIO', field: 'COL 7' },
                { headerName: 'FINE', field: 'COL 8' }
 ]);

 const defaultColDef = useMemo( ()=> ({
  sortable: true,
  filter: true
}), []);
//fetch dati dall'index ed analisi del risultato
useEffect(() => {
  let isMounted = true;

  const fetchData = async () => {
    try {
      const response = await fetch('index2.php');

      if (!response.ok) {
        throw new Error(`Errore nella richiesta: ${response.status}`);
      }

      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        const rowData = await response.json();
        
        if (isMounted) {
          console.log('Dati ottenuti da index.php:', rowData);
          setRowData(rowData);
        }
      } else {
        throw new Error('La risposta non รจ di tipo JSON');
      }
    } catch (error) {
      console.error('Errore durante la richiesta a index.php:', error);
    }
  };

  fetchData();

  return () => {
    // Cleanup function, eseguita quando il componente si smonta
    isMounted = false;
  };
}, []);
//
  return (
    <div className='ag-theme-alpine-dark' style={{height: 500}}>
      <AgGridReact
        rowData={rowData}
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        animateRows={true}
        />
    </div>
  );
}

export default App;

and this is th index.php

<?php

$servername = "127.0.0.1";
$username = "gaetano";
$password = "gaetano";
$dbname = "ompm";

// Creare una connessione
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Verificare la connessione
if (!$conn) {
    die("Connessione al database non riuscita: " . mysqli_connect_error());
}

// Query connessione a tabella
$query = "SELECT * FROM datidaimportare";
$result = mysqli_query($conn, $query);

// Controllo degli errori nella query
if (!$result) {
    die("Errore nella query: " . mysqli_error($conn));
}

// Creazione di un array per i risultati
$data = array();

while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

// Chiudi la connessione al database
mysqli_close($conn);

// Imposta l'intestazione Content-Type in modo che il client riconosca i dati come JSON
header('Content-Type: application/json');

// Restituisci i dati come JSON
echo json_encode($data);
?>

2

Answers


  1. One usual issue in setups is CORS. If your React app is served from a different domain or port than your PHP server, the browser will block the request due to security reasons. So you can try add CORS headers in your PHP script. You can add the following lines at the beginning of your index.php file:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    

    Maybe you can try to check the columnDefs state, it seems to be misconfigured.

    The fields shouldn’t match the keys of your JSON data? Assuming your PHP script returns data with keys like id, nome, cognome, etc., your column definitions should look like this:

    const [columnDefs, _setColumnDefs] = useState([
      { headerName: 'ID', field: 'id' },
      { headerName: 'NOME', field: 'nome' },
      { headerName: 'COGNOME', field: 'cognome' },
      // Add others fields as per your data response
    ]);
    
    Login or Signup to reply.
  2. Responses from PHP will be ok if it just reach the index.php , it means it may return bad data but still response ok. Go to inspect network tab and find the FILE NAME ( index.php) and look at tab (preview), you will see what your PHP file is showing to the react. enter image description here

    if there is an error loading data, the response will not be JSON and it throws error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search