How can PHP return data to the same location?

In PHP, data can be passed to the same location using either forms or URL parameters. If you want to display data on the same page, you can achieve this by submitting a form or using AJAX.

Here are some sample codes:

  1. Submit data using a form.
<form action="same_page.php" method="post">
    <input type="text" name="data">
    <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $data = $_POST["data"];
    echo "Data submitted: " . $data;
}
?>
  1. Transfer data using URL parameters.
<a href="same_page.php?data=hello">Click here</a>

<?php
if (isset($_GET["data"])) {
    $data = $_GET["data"];
    echo "Data passed: " . $data;
}
?>
  1. Use AJAX to asynchronously send data and return it to the same location.
<div id="result"></div>
<input type="button" value="Submit" onclick="submitData()">

<script>
function submitData() {
    var data = "hello";
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "same_page.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("result").innerHTML = xhr.responseText;
        }
    };
    xhr.send("data=" + data);
}
</script>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $data = $_POST["data"];
    echo "Data submitted: " . $data;
}
?>

These codes can help you return the data to the same position. Depending on your specific needs, you can choose the appropriate method to achieve it.

Leave a Reply 0

Your email address will not be published. Required fields are marked *