Creating a javascript alert with php that has a php variable inside?

Creating a javascript alert with php that has a php variable inside?

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

Stefan Bogdanescu

Founder & Senior Architect

Escaping Data to Bridge PHP and JavaScript

The core issue in your approach isn't that you are mixing PHP and JavaScript; it is how the data flows between them. When you use die() inside a function, the script terminates immediately, and any subsequent HTML or code never executes. However, even if we remove the die() call to allow the browser to render the page, your specific line of code:

echo '<script type="text/javascript"> alert('.$error.') </script>';

will almost certainly break before it reaches the user. The problem lies in how PHP treats special characters within strings versus how JavaScript interprets them. If $error contains a single quote (') or a double quote ("), your script breaks immediately because the browser thinks the string has ended prematurely.

For example, if your error message is "Invalid email address", the output becomes:
alert(Invalid email address)
JavaScript sees alert( followed by text it doesn't expect until it hits the closing parenthesis of the argument, but the structure collapses if quotes are involved. If the error was "It can't be done", the output would look like alert(It can't be done), causing a syntax error because the single quote inside the string closes the JavaScript string literal unexpectedly.

To fix this, you must escape the data before echoing it into a script block. The standard solution is to use PHP's built-in escaping functions designed specifically for this context. The function js_encode() does not exist in the standard PHP core, so you cannot rely on a generic name without implementation details. Instead, you should use htmlspecialchars or json_encode.

If you choose htmlspecialchars, you must be careful about the encoding type and quote style. Since your script block uses double quotes ("), you need to escape single quotes if they exist in the string, but htmlspecialchars by default only handles HTML entities. You would have to manually handle the JavaScript-specific escaping or use a different approach.

The most robust solution is using json_encode(). This function is designed specifically for serializing PHP data structures into valid JSON strings. It automatically handles quotes, escapes backslashes, and ensures the resulting string is safe to be embedded in JavaScript code.

Here is the corrected implementation:

function died($error) {
    // Encode the error message as a JSON string
    $safeError = json_encode($error);
    
    echo '<script type="text/javascript">' . "\n";
    echo 'alert(' . $safeError . ');' . "\n";
    echo '</script>';
    
    // Stop execution to prevent any further output or errors
    exit(1); 
}

// Example usage
$died("Invalid input"); 

In this example, json_encode ensures that if $error contains a single quote like "It's not working", it transforms the string into "It\\'s not working". The resulting JavaScript code becomes valid: alert("It\'s not working"). Note that we switched to single quotes in the outer JavaScript string in the output because the JSON encoder handles the internal quoting logic, but strictly speaking, json_encode outputs double quotes by default.

Actually, a more concise way to write this without relying on newline formatting for readability is:

function died($error) {
    echo '<script type="text/javascript">alert(' . json_encode($error) . ');</script>';
    exit();
}

This approach guarantees that the string passed to alert() is syntactically correct regardless of what characters are inside the variable. It also handles Unicode characters correctly, preventing encoding mismatches between your server and the browser.

One trade-off to consider is user experience. Using exit() or die() after an alert halts all page processing. If you are using a framework like Laravel, this might bypass middleware or error logging mechanisms depending on how the exception handler is configured. In such environments, it is often better to return a response code (e.g., HTTP 422 Unprocessable Entity) and let the frontend handle the display logic via AJAX or form validation attributes, rather than forcing a full page reload with a JavaScript alert.

However, for legacy forms or simple scripts where you need immediate visual feedback, this pattern remains valid provided data escaping is handled rigorously. Always prioritize security; never trust user input directly into alert() without encoding it first, as unescaped input could theoretically lead to XSS vulnerabilities if the error message contained malicious script tags (though alert generally mitigates this by stripping content, proper encoding is still mandatory).

Our network