Get data from mysql database using php and jquery ajax

Get data from mysql database using php and jquery ajax

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

Stefan Bogdanescu

Founder & Senior Architect

Debugging Cross-Domain AJAX Requests in Legacy PHP Projects

When a script functions perfectly in isolation but fails upon being called via an asynchronous request, the culprit is rarely the database logic itself. In your specific scenario where process.php works when run directly but returns nothing or throws an error during an AJAX call, the issue almost certainly lies in how the data is being sent and received between the client and server.

Your JavaScript code attempts to send a POST request with a property named action. However, you are assigning the variable showroom (which is undefined) to that key instead of passing the string "showroom". This results in your PHP script receiving an empty or null value for $action, causing the conditional check if($action=="showroom") to fail silently. Consequently, the PHP file executes but outputs nothing because the logic inside the if block is never triggered.

To fix this, you must ensure the data object passed to jQuery contains the correct string literal. In your JavaScript, change data:{action:showroom} to data:{action:"showroom"}. This ensures that when the request reaches your server, $_POST["action"] will hold the exact value your PHP logic expects.

Beyond syntax errors, there is a critical architectural decision you must make regarding how the response is handled. Your current success callback uses .html(data) to inject content directly into the DOM. This approach works only if your PHP script echoes raw HTML markup that matches the expected structure of an unordered list. If your PHP script outputs text without proper escaping or if it encounters an error, the HTML will break immediately in the browser.

A more robust pattern involves returning a JSON response from process.php. This decouples the data structure from the presentation layer and allows your JavaScript to handle success, failure, and errors uniformly. Modify your PHP file to use header('Content-Type: application/json') before echoing any output. Inside the logic, instead of looping through rows and echoing <li> tags directly, construct a JSON array or object representing the data.

<?php
// ... database connection code ...

$action = $_POST["action"];

if ($action == "showroom") {
    $query = "SELECT * FROM user";
    $result = mysqli_query($link, $query);

    if (!$result) {
        echo json_encode(["error" => "Database query failed"]);
        exit;
    }

    $users = [];
    while ($row = mysqli_fetch_assoc($result)) {
        // Use array keys instead of string interpolation for safety
        $users[] = [
            "name" => $row["name"],
            "id" => $row["id"] 
        ];
    }

    echo json_encode(["status" => "success", "data" => $users]);
} else {
    echo json_encode(["error" => "Invalid action"]);
}
?>

On the client side, update your AJAX call to parse this JSON response. You can use $.ajax with a callback that checks for the status field before attempting to render the list. If the data is valid, iterate through the array and append elements to the #content div dynamically.

Another common pitfall in legacy PHP applications is the lack of header flushing or output buffering issues. Since your original code used echo inside a loop without setting headers beforehand, any whitespace (like a newline) before the opening <?php tag would corrupt the response if you were trying to return JSON. Always ensure no characters appear before the first line of code in PHP files intended for API consumption.

Security is also a significant concern when exposing database queries via AJAX. Your current implementation retrieves all columns from the user table without sanitization. While this might work for local development, returning sensitive user data via an unauthenticated endpoint is dangerous. Always verify the user's session or authentication status before executing read queries, and consider using prepared statements if you ever add dynamic filtering to prevent SQL injection.

If you decide to migrate away from vanilla PHP and jQuery eventually, frameworks like Laravel offer built-in support for these patterns through Eloquent ORM and Blade templating, which handle data escaping and routing more securely. For instance, a route in Laravel could accept the JSON payload and return a formatted response automatically, reducing the boilerplate code required in your process.php.

Our network