Get variable from PHP file using JQuery/AJAX

Get variable from PHP file using JQuery/AJAX

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

Stefan Bogdanescu

Founder & Senior Architect

Get variable from PHP file using JQuery/AJAX

You are trying to extract a specific variable, $advert, from a server-side script (analysis.php) and inject it directly into your chat interface without reloading the page. The core issue here is architectural: your current setup sends data via a POST request but expects the response to be a standard HTML page or nothing at all. To achieve this dynamic behavior, you need to switch analysis.php from returning an HTML document to returning a raw JSON payload, and configure jQuery to handle that specific format.

Currently, analysis.php executes PHP logic to query MySQL and assigns the result to $advert. If this file currently outputs HTML (even if it's just blank) or redirects, your JavaScript won't receive the data. You must explicitly output valid JSON. A common mistake beginners make is echoing the variable directly without ensuring it is wrapped in a JSON object, especially if the value contains special characters that could break the script.

Here is how you should modify analysis.php to return the data correctly:

<?php
// ... your existing logic here ...
// $advert = $row['adverts']; 

// Ensure 'advert' is defined. If it might be null or empty, handle that case.
$data = ['advert' => $advert];

// Output raw JSON and terminate script execution immediately
header('Content-Type: application/json');
echo json_encode($data);
exit; 
?>

The header('Content-Type: application/json') line is critical. It tells the browser and the client-side JavaScript that the response contains structured data, not an HTML page to render. The exit command ensures no subsequent code (like including a footer or printing error logs) pollutes the JSON output.

On the client side, you need to intercept the form submission before it performs a standard POST reload. In your ajax-chat.html, you should add an event listener for the submit button within your script.js file. Using jQuery's .on() method is best practice to avoid issues with multiple script loads or re-initialization:

$(document).ready(function() {
    $('#submitForm').on('submit', function(event) {
        // Prevent the form from submitting normally (which would reload the page)
        event.preventDefault();

        var chatText = $('#chatText').val();

        $.ajax({
            type: 'POST',
            url: 'analysis.php',
            data: { 
                'chatText': chatText 
                // Add other necessary parameters here if your analysis.php expects them
            },
            success: function(response) {
                // response is now a JSON object, not a string or HTML
                var advert = response.advert; 

                // Check if the value exists before appending to avoid breaking the DOM
                if (advert !== undefined && advert !== null) {
                    $('#chatLineHolder').append(
                        '<div class="chat-message">' + advert + '</div>'
                    );
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', error);
                // Handle server errors gracefully here
            }
        });
    });
});

This approach prevents the page from jumping back to the top after submission and keeps the chat interface responsive. One specific pitfall to watch out for is XSS (Cross-Site Scripting). Since you are appending the advert variable directly into an HTML element using string concatenation ('<div>' + advert + '</div>'), a malicious user could inject script tags if they control the input or the database content. Always escape HTML entities before rendering untrusted data.

function escapeHtml(text) {
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

$('#chatLineHolder').append('<div class="chat-message">' + escapeHtml(advert) + '</div>');

If your database query returns complex data structures (arrays or nested objects), json_encode will handle them correctly, and you can parse the specific property using dot notation in JavaScript. This method ensures that data flows securely from the MySQL database through PHP to your DOM elements without requiring a full page reload.

Our network