I have an HTML form and send data to php file when hitting submit button.
$.ajax({
url: "text.php",
type: "POST",
data: {
amount: amount,
firstName: firstName,
lastName: lastName,
email: email
},
dataType: "JSON",
success: function (data) {
console.log("ok");
$("#result").text(data);
}
});
In PHP:
<?php
$amount = $_POST["amount"];
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
if(isset($amount)){
$data = array(
"amount" => $amount,
"firstName" => $firstName,
"lastName" => $lastName,
"email" => $email
);
echo json_encode($data);
}
?>
The result is [object object]. I want a type like:
{"Amount":"12.34", "FirstName":"Any", "LastName":"Tester", "Email":"[email protected]"}
What have I done wrong?
The result is [object object]
... yes, that's what you'll get if JS casts an object to a string. Your JSON may be correct; you're just not examining it properly. Try usingconsole.log()
instead. Also, use the dev tools to look at the http response that PHP sends back -- you should be able to see exactly what the data looks like.