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?
Code example with JSON.stringify:
<html>
<head>
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
url: "text.php",
type: "POST",
data: {
amount: $("#amount").val(),
firstName: $("#firstName").val(),
lastName: $("#lastName").val(),
email: $("#email").val()
},
dataType: "JSON",
success: function (jsonStr) {
$("#result").text(JSON.stringify(jsonStr));
}
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form name="contact" id="contact" method="post">
Amount: <input type="text" name="amount" id="amount"/><br/>
firstName: <input type="text" name="firstName" id="firstName"/><br/>
lastName: <input type="text" name="lastName" id="lastName"/><br/>
email: <input type="text" name="email" id="email"/><br/>
<input type="button" value="Get It!" name="submit" id="submit"/>
</form>
</body>
</html>
<?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);
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With