If the session of the page with data is terminated while extracting data with Ajax

Hello,

i have an html table,
In the ajax page, I create the lines with <tr><td></td></tr> and import them with ajax, and the comment loaded into the <tbody id="ajaxtarget"></tbody> field

In addition, there is a search option on the page, and the results come immediately when entering the text to be searched.

There is no problem with this working

The problem is:
If the page is open for a long time, the session is terminated.
However, since the page is open, it is not understood that the session has ended, and when text is entered in the search field, the ajax waiting data icon works and the member waits for the data to come.

However, the session has expired, it is necessary to log in again, but the member is not aware of it.

When I log in to the ajax page directly from the url, it redirects me to the login page
I added “console.log(data)” to the ajax code, no data is coming (when logged out and search text entered)

When logged out, and the search text is entered, you need to log in again warning how to do?
Or what should be the solution in such a situation.

I see the following when typing search text on console screen

XHR POST http://name.com/ajaxpage.php
XHR GET http://name.com/login.php?last=/ajaxpage.php

Note: I am using json in ajax

I did something like below, it worked for now, but I don’t know what the truth is

in login php
if(isset($_GET['last']) && $_GET['last'] == '/ajaxpage.php'){
$json = array(
	"out"	=> 1,
);
echo json_encode($json);
exit;
}

in ajax
    success: function (data) {
      if (data.out==1){
        window.location.href = "login.php";
      }else{
	  ....
	  ...

I don’t know exactly what you are trying to do, but login status and retrieving data should be two different things. I personally just check to see if a user is logged in.

Example →

<?php
require_once __DIR__ . '/../config/config.php';
require_once "vendor/autoload.php";

use Intervention\Image\ImageManagerStatic as Image;
use brainwave\{
    ErrorHandler,
    Database,
    LoginRepository as Login,
    ImageContentManager
};

$errorHandler = new ErrorHandler();

// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);

$database = new Database();
$pdo = $database->createPDO();

// Check to see user is login in, if not redirect them to the home or login in page:
$login = new Login($pdo);
if (!$login->check_login_token()) {
    header('location: index.php');
    exit();
}
?>

then I use my script to retrieve the data →

'use strict';
//edit_puzzle.js
(function () {
    document.addEventListener("DOMContentLoaded", function () {
        const searchForm = document.getElementById("searchForm");
        const editForm = document.getElementById("data_entry_form");
        const id = document.getElementById("id");
        const image_for_edit_record = document.getElementById("image_for_edited_record");
        const category = document.getElementById("category");
        const difficulty_level = document.querySelector('#difficulty_level');
        const description = document.getElementById('description');
        const resultInput = document.getElementById("searchTerm");



        async function displayRecord(searchTerm = null) {
            const requestData = {};
            if(searchTerm !== null) requestData.searchTerm = searchTerm;

            try {
                const response = await fetch("search_puzzle_records.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(requestData),
                });

                const data = await response.json();
                console.log(data); // Add this line
                if (data.message) {
                    resultInput.value = '';
                    resultInput.placeholder = data.message;
                } else if (data.error) {
                    console.error(data.error);
                } else {
                    const row = data[0];
                    console.log('row', row);
                    id.value = row.id;
                    image_for_edit_record.src = row.image_path;
                    image_for_edit_record.alt = "Puzzle Image";
                    // Set the value for the category
                    for (let option of category.options) {
                        if (option.value === row.category) {
                            option.selected = true;
                            break;
                        }
                    }

                    // Set the value for the difficulty level
                    for (let option of difficulty_level.options) {
                        if (option.value === row.difficulty_level) {
                            option.selected = true;
                            break;
                        }
                    }
                    description.textContent = row.description;
                }
            } catch (error) {
                console.error("Error:", error);
            }
        }

        searchForm.addEventListener("submit", function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();

            // Get the value of the search term input field and the select box
            const searchTermInput = document.getElementById("searchTerm").value;


            // Use the input value if it's not empty, otherwise use the select value
            const searchTerm = searchTermInput !== "" ? searchTermInput : null;


            // Call the displayRecord function with the search term and selected heading
            displayRecord(searchTerm);
        });


        // Add an event listener to the edit form's submit event
        editForm.addEventListener("submit", async function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();
            event.stopImmediatePropagation();
            // Create a FormData object from the edit form
            const formData = new FormData(editForm);
            console.log("form data", formData);
            // Send a POST request to the edit_update_blog.php endpoint with the form data
            const response = await fetch("update_puzzle_records.php", {
                method: "POST",
                body: formData,
            });

            // Check if the request was successful
            if (response.ok) {
                const result = await response.json();
                console.log(result);
                // If the response has a "success" property and its value is true, clear the form
                if (result.success) {
                    resultInput.value = '';          // Clear the current value of the search input field
                    resultInput.placeholder = "New Search"; // Set the placeholder to `New Search`
                    image_for_edit_record.src = "";
                    image_for_edit_record.alt = "";
                    document.getElementById("description").textContent = "";
                    document.getElementById("difficulty_level").selectedIndex = 0; // set to the first option
                    document.getElementById("category").selectedIndex = 0; // set to the first option

                    editForm.reset(); // Resetting the edit form
                    searchForm.reset(); // Resetting the search form
                }

            } else {
                console.error(
                    "Error submitting the form:",
                    response.status,
                    response.statusText
                );
                // Handle error response
            }
        });


    });
})();

I use FETCH / PHP / JavaScript as I find FETCH (jQuery has something similar, but I use Vanilla JavaScript) →

'use strict';
//edit_puzzle.js
(function () {
    document.addEventListener("DOMContentLoaded", function () {
        const searchForm = document.getElementById("searchForm");
        const editForm = document.getElementById("data_entry_form");
        const id = document.getElementById("id");
        const image_for_edit_record = document.getElementById("image_for_edited_record");
        const category = document.getElementById("category");
        const difficulty_level = document.querySelector('#difficulty_level');
        const description = document.getElementById('description');
        const resultInput = document.getElementById("searchTerm");



        async function displayRecord(searchTerm = null) {
            const requestData = {};
            if(searchTerm !== null) requestData.searchTerm = searchTerm;

            try {
                const response = await fetch("search_puzzle_records.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(requestData),
                });

                const data = await response.json();
                console.log(data);
                if (data.message) {
                    resultInput.value = '';
                    resultInput.placeholder = data.message;
                } else if (data.error) {
                    console.error(data.error);
                } else {
                    const row = data[0];
                    console.log('row', row);
                    id.value = row.id;
                    image_for_edit_record.src = row.image_path;
                    image_for_edit_record.alt = "Puzzle Image";
                    // Set the value for the category
                    for (let option of category.options) {
                        if (option.value === row.category) {
                            option.selected = true;
                            break;
                        }
                    }

                    // Set the value for the difficulty level
                    for (let option of difficulty_level.options) {
                        if (option.value === row.difficulty_level) {
                            option.selected = true;
                            break;
                        }
                    }
                    description.textContent = row.description;
                }
            } catch (error) {
                console.error("Error:", error);
            }
        }

        searchForm.addEventListener("submit", function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();

            // Get the value of the search term input field and the select box
            const searchTermInput = document.getElementById("searchTerm").value;


            // Use the input value if it's not empty, otherwise use the select value
            const searchTerm = searchTermInput !== "" ? searchTermInput : null;


            // Call the displayRecord function with the search term and selected heading
            displayRecord(searchTerm);
        });


        // Add an event listener to the edit form's submit event
        editForm.addEventListener("submit", async function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();
            event.stopImmediatePropagation();
            // Create a FormData object from the edit form
            const formData = new FormData(editForm);
            console.log("form data", formData);
            // Send a POST request to the edit_update_blog.php endpoint with the form data
            const response = await fetch("update_puzzle_records.php", {
                method: "POST",
                body: formData,
            });

            // Check if the request was successful
            if (response.ok) {
                const result = await response.json();
                console.log(result);
                // If the response has a "success" property and its value is true, clear the form
                if (result.success) {
                    resultInput.value = '';          // Clear the current value of the search input field
                    resultInput.placeholder = "New Search"; // Set the placeholder to `New Search`
                    image_for_edit_record.src = "";
                    image_for_edit_record.alt = "";
                    document.getElementById("description").textContent = "";
                    document.getElementById("difficulty_level").selectedIndex = 0; // set to the first option
                    document.getElementById("category").selectedIndex = 0; // set to the first option

                    editForm.reset(); // Resetting the edit form
                    searchForm.reset(); // Resetting the search form
                }

            } else {
                console.error(
                    "Error submitting the form:",
                    response.status,
                    response.statusText
                );
                // Handle error response
            }
        });


    });
})();

Here’s my search PHP thrown in →

<?php

// Send a response to the client with the content type set to application/json.
header('Content-Type: application/json');

// Include the necessary files and classes for this script.
require_once __DIR__ . '/../config/config.php';
require_once "vendor/autoload.php";

// Use some classes for error handling, database connection and login-related actions.
use brainwave\ErrorHandler;
use brainwave\Database;
use brainwave\LoginRepository as Login;

// Instantiate an ErrorHandler object.
$errorHandler = new ErrorHandler();

// Set a custom exception handler function.
set_exception_handler([$errorHandler, 'handleException']);

// Create a new Database object and establish a PDO connection.
$database = new Database();
$pdo = $database->createPDO();

// Instantiate a Login object.
$login = new Login($pdo);

// Main try-catch block.
try {
    // Get the request body and decode it as JSON.
    $request = json_decode(file_get_contents('php://input'), true);

    // Extract the search term and heading from the request, if they exist.
    $searchTerm = $request['searchTerm'] ?? null;


    // If a search term was provided, use a full-text search on the 'content' field.
    // Before this can work, you'll need to make sure your content column is indexed for full-text searching.
    // You can do this with the following SQL command:
    // Example:
    // ALTER TABLE puzzle_images ADD FULLTEXT(description);
    if($searchTerm !== null) {
        $sql = "SELECT * FROM puzzle_images WHERE MATCH(description) AGAINST(:searchTerm IN NATURAL LANGUAGE MODE) LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':searchTerm', $searchTerm);
    } else {
        throw new Exception("No valid search term or heading provided");
    }

    // Execute the prepared statement.
    $stmt->execute();

    // Fetch the results and handle them as needed.
    $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If results were found, return them to the client as JSON.
    if ($row) {
        echo json_encode($row);
    } else {
        echo json_encode(['message' => 'No results found.']);
    }

// Catch any exceptions that occur during database interaction.
} catch (PDOException $e) {
    echo json_encode(['error' => $e->getMessage()]);
}

I use async/await so that the data wouldn’t be missed (I am not using the correct term)
Hope that helps a little?

Oh, error messages shouldn’t be displayed, but either logged in or emailed.

1 Like

First of all, happy birthday,
This is very professional not suitable for us :grinning: :grinning: :grinning:
When the user leaves the page open, does the session automatically close and redirect to the login page?

Sponsor our Newsletter | Privacy Policy | Terms of Service