javascriptphpresponsereloadjsonencode

Is there a way to prevent echo json_encode() return the JSON response with the whole page when submitting form to the same PHP script?


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?


Solution

  • 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();
        }        
    }