OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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?

  • Thread starter Thread starter Developer
  • Start date Start date
D

Developer

Guest
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:

Code:
<?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?

<p>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:</p>
<pre><code><?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>
</code></pre>
<p>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?</p>
 

Latest posts

I
Replies
0
Views
1
Isaac P. Liu
I
U
Replies
0
Views
1
user3658366
U
G
Replies
0
Views
1
Giampaolo Levorato
G
M
Replies
0
Views
1
Marcelo Rodrigo Nascimento
M
Top