skip to Main Content

I’ve got this only index.php file in the project. I know I should separate the logic from the view, use different files for PHP, JS and HTML. This is only a test:

<?php
    if($_SERVER["REQUEST_METHOD"] == "POST") {        
        if(isset($_POST["item"]) && $_POST["item"] == "new") {
            $description = filter_input(INPUT_POST, trim("description"));
            echo json_encode($description);
        }        
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Itens</title>
</head>
<body>
    <form method="post">
        <input type="text" name="description" placeholder="Description">
        <button type="submit">Add Item</button>
    </form>

    <script>
        const form = document.querySelector("form")
        form.addEventListener('submit', async (e) => {
            e.preventDefault()
            const item = "new"
            const description = form.description.value            
            const formData = new FormData()
            formData.append("item", item)
            formData.append("description", description)            
            try {
                await fetch('./index.php', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json, text/plain, */*'                
                    }
                })
                .then((res) => res.json())
                .then((data) => {                    
                    alert(data)                    
                })
            } 
            catch(error) {}
        })
    </script>
    
</body>
</html>

The echo json_encode() works and sends the response, but also sends the whole page, reloading the index.php, which makes impossible work with the response value in the JavaScript fetch code. When working with echo json_encode() in a different script from code who called it, that doesn’t happen, of course. Is it possible to fix this keeping this one file structure?

2

Answers


  1. yeah, put it inside the HTML

    <?php
        $jsonData = {};
    
        if($_SERVER["REQUEST_METHOD"] == "POST") {        
            if(isset($_POST["item"]) && $_POST["item"] == "new") {
                $description = filter_input(INPUT_POST, trim("description"));
                $jsonData = json_encode($description);
            }        
        }
    ?>
    
    <script>
      const json = <?php echo $jsonData; ?>
    </script>
    <pre><?php echo $jsonData; ?></pre>
    

    The cleaner way as you menitioned (REST api) is to put the json output into a seperate php script and use javascript to request the json.

    Login or Signup to reply.
  2. All you need:

    1. add square bracket (to make array used for function ‘json_encode’)

      echo json_encode([$description]);

    2. add exit(); as Arun A S wrote

    so finally top part will be:

    if($_SERVER["REQUEST_METHOD"] == "POST") {        
        if(isset($_POST["item"]) && $_POST["item"] == "new") {
            $description = filter_input(INPUT_POST, trim("description"));
            echo json_encode([$description]);
            exit();
        }        
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search