Retrieve data without refresh

 To retrieve the agent ID in `print.php` without a page refresh, you can pass the agent ID as a parameter in the request using JavaScript. Here's how you can modify the code to achieve that:


1. **HTML/JavaScript (frontend)**:


```html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Print Button</title>

</head>

<body>

    <button id="printButton">Print</button>

    <script>

        document.getElementById("printButton").addEventListener("click", function() {

            // Assuming you have fetched the agent ID and stored it in a variable called agentId

            var agentId = "your_agent_id_here";

            // Creating a form element dynamically

            var form = document.createElement("form");

            // Setting form attributes

            form.setAttribute("method", "post");

            form.setAttribute("action", "print.php");

            // Creating a hidden input field for the agent ID

            var hiddenInput = document.createElement("input");

            hiddenInput.setAttribute("type", "hidden");

            hiddenInput.setAttribute("name", "agentId");

            hiddenInput.setAttribute("value", agentId);

            // Appending the hidden input field to the form

            form.appendChild(hiddenInput);

            // Appending the form to the body and submitting it

            document.body.appendChild(form);

            form.submit();

        });

    </script>

</body>

</html>

```


2. **PHP (backend)**:


```php

<?php

// print.php


// Retrieving the agent ID from the POST request

$agentId = $_POST['agentId'];


// Assuming you have a database connection established already


// Assuming you have a SQL query to fetch details based on the agent ID

$query = "SELECT * FROM your_table WHERE agent_id = '$agentId'";


// Executing the SQL query

$result = mysqli_query($conn, $query);


// Checking if the query was successful

if ($result) {

    // Fetching data and printing it, or performing any other actions

    while ($row = mysqli_fetch_assoc($result)) {

        // Printing details or processing data

        echo "Agent ID: " . $row['agent_id'] . "<br>";

        echo "Name: " . $row['name'] . "<br>";

        // Add other fields as needed

    }

} else {

    // Error handling if the query fails

    echo "Error: " . mysqli_error($conn);

}


// Closing the database connection

mysqli_close($conn);

?>

```


This code dynamically creates a form element, sets its attributes, adds a hidden input field for the agent ID, appends the form to the body, and submits it. This way, the agent ID is passed to `print.php` without a page refresh. Adjust the code as per your specific requirements and structure.

Previous
Next Post »