Why jQuery Displays [object Object] When Parsing JSON Responses
When you submit a form via $.ajax and receive a JSON response, expecting to see the raw string representation of that data in your HTML is a common misconception. In your specific case, the console logs "ok" and attempts to populate #result, but instead of the formatted object {...}, you are seeing [object Object]. This behavior isn't caused by PHP's json_encode() function; it is entirely how JavaScript handles string interpolation within template literals or standard string concatenation.
The root cause lies in this line of your jQuery success callback:$("#result").text(data);
When you pass the variable $data directly to .text(), jQuery calls .toString() on that object to determine what text to insert into the DOM element. In JavaScript, calling .toString() on a standard Object (or an array) does not return its JSON representation or its internal keys and values. It returns the literal string [object Object].
To get the desired outputâ{"Amount":"12.34", "FirstName":"Any"...}âyou must explicitly convert the data object into a JSON-formatted string before assigning it to the DOM element. You cannot rely on implicit conversion.
Fixing the JavaScript Client-Side Logic
The most direct fix is to use JSON.stringify() inside your success callback. This function takes an object and returns a JSON string representation of that object, which is exactly what jQuery's .text() method expects if you want to render raw JSON text in the browser.
Update your jQuery code as follows:
$.ajax({
url: "text.php",
type: "POST",
data: {
amount: amount,
firstName: firstName,
lastName: lastName,
email: email
},
dataType: "JSON", // Keep this; jQuery will parse the response automatically
success: function (data) {
console.log("ok");
// Convert the parsed object back to a JSON string for display
$("#result").text(JSON.stringify(data));
}
});
Note that you should keep dataType: "JSON". Even though text.php sends raw text, jQuery automatically parses incoming JSON responses into native JavaScript objects when this flag is present. This ensures that $data inside the callback is a usable object, which you then stringify specifically for display purposes.
Validating Your PHP Backend
Your PHP implementation is technically correct regarding the encoding process. The snippet:
echo json_encode($data);
will output exactly what you need, provided json_encode() hasn't hit any edge cases with special characters in your input fields (though json_encode handles UTF-8 well by default).
However, there is a subtle logic gap in your PHP code regarding the if(isset($amount)) check. If a user submits the form without filling the amount field, $_POST["amount"] will be undefined or an empty string depending on how the HTML form is structured (e.g., if the input has no default value).
If the form inputs do not have a name attribute or are hidden fields missing from the request, isset() might pass but return an empty value. To ensure the JSON response remains valid and consistent, it is often safer to initialize variables before checking them:
<?php
// Initialize variables to null or empty strings to prevent undefined index warnings
$amount = $_POST["amount"] ?? '';
$firstName = $_POST["firstName"] ?? '';
$lastName = $_POST["lastName"] ?? '';
$email = $_POST["email"] ?? '';
// Check if we actually received data, or handle the empty case appropriately
if (empty($amount) && empty($firstName)) {
echo json_encode(["error" => "Missing required fields"]);
exit;
}
$data = [
"Amount" => $amount,
"FirstName" => $firstName,
"LastName" => $lastName,
"Email" => $email
];
echo json_encode($data);
?>
Note the key change: json_encode converts your associative array keys to camelCase by default in many languages, but PHP preserves them exactly as written. Your desired output uses CamelCase keys (Amount, FirstName). In your original code, you used lowercase keys ("amount", "firstName"). If the requirement is strictly CamelCase in the JSON response, ensure the keys in the $data array match that casing explicitly.
Handling Data Types and Escaping
One potential pitfall arises if your input data contains quotes or special characters. json_encode automatically escapes these within the resulting string, so "Email": "a.test@something.com" will become "Email": \"a.test@something.com\" in the raw HTML output. This is standard JSON behavior and usually fine for display purposes unless you are rendering this into a template engine like Blade or Twig where further escaping might occur.
If you are transitioning to a modern PHP stack, consider using Laravel's response()->json() method. It handles headers and encoding automatically:
use Illuminate\Http\Request;
return response()->json([
'Amount' => $amount,
'FirstName' => $firstName,
]);
This approach abstracts the Content-Type header setting (application/json) which is crucial for strict JSON consumption. However, for simple scripts like text.php, raw echo json_encode() remains a valid and performant solution.
The primary fix remains on the client side: always use JSON.stringify() when you need to display a parsed JSON object as text in the DOM.