How to query database using javascript?

How to query database using javascript?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to query database using javascript?

You want a form in a popup to update a database record and immediately change a link on the main page without refreshing. That is an asynchronous pattern, but it requires a specific architecture because JavaScript cannot directly access your server-side PHP variables or execute your existing database queries. The browser runs in a sandboxed environment; it can only talk to your application via HTTP requests.

To achieve this, you need to decouple the data retrieval logic from the presentation layer. In your current setup, the $publish variable exists only on the server. When the page loads, PHP executes the query and decides which HTML link to print. To change that link dynamically, the JavaScript needs a fresh value from the database that reflects the most recent state.

The standard approach involves three steps:

  1. Endpoint Creation: Create a dedicated API endpoint (e.g., GET /api/check-published) that returns the current status of the record as JSON. This replaces the server-side PHP logic of checking $publish.
  2. Initial Load: On page load, call this endpoint to determine whether to show the "Publish" or "Edit" link initially.
  3. Event Handling: After the popup form submits successfully, trigger a new call to the same endpoint to update the UI.

Here is how you would implement this using jQuery, assuming you have a route defined in your PHP application that returns JSON based on the current database state:

// Initial check on page load
$(document).ready(function() {
    $.getJSON('/api/check-published', function(response) {
        if (response.published === true) {
            $('#publish-link').hide();
            $('#edit-link').show();
        } else {
            $('#publish-link').show();
            $('#edit-link').hide();
        }
        
        // Store the current state if you need to revert logic later
        window.currentPublishedState = response.published;
    });
});

// Function called after form submission in the popup
function updateLinkAfterPublish() {
    $.getJSON('/api/check-published', function(response) {
        if (response.published === true) {
            $('#publish-link').hide();
            $('#edit-link').show();
        } else {
            $('#publish-link').show();
            $('#edit-link').hide();
        }
    });
}

// Hook this into your popup form's success handler
$('#publish-form').on('submit', function(e) {
    e.preventDefault(); // Prevent default form submission
    
    $.post('/api/publish-data', $(this).serialize(), function(data, status) {
        if (status === 'success') {
            updateLinkAfterPublish();
            
            // Optional: Close the popup here
            // $('#publish-modal').modal('hide'); 
        }
    });
});

The critical detail here is the endpoint /api/check-published. You must replace your existing PHP logic that checks $publish with a function that returns JSON. Do not return HTML fragments or redirect; the client needs structured data to make decisions. A typical controller method might look like this:

// Example PHP Controller Logic
public function getPublishedStatus() {
    // Query the database table directly here
    $record = DB::table('your_table')->first();
    
    return response()->json([
        'published' => !empty($record->publish_field)
    ]);
}

Trade-offs and Pitfalls

A common mistake is trying to pass the new data back from the popup via a hidden input field or URL parameter. While technically possible, this bypasses the database reality. If two users edit simultaneously, passing state in the UI will cause race conditions where one user's changes overwrite another's without the server knowing. Always re-query the database on the server side to validate the current state before updating the UI.

Another consideration is performance. If you are checking this status on every keystroke or frequent event, consider debouncing your AJAX calls. However, for a simple form submit, a single request after success is negligible overhead.

If you are working within a Laravel environment, leveraging its built-in resource controllers and JSON responses makes this seamless. The architecture remains the same regardless of the framework: separate concerns between data persistence (PHP/Database) and user interaction (JavaScript). This ensures that your link always reflects the ground truth stored in the database, not the last known state from a previous page load or popup interaction.

Our network