I have a small feedback form with two inputs. I want the error message to append to one another in the same div using JQuery. The error message works fine if there is only one error message, but when I return two json objects, both messages will not display at the same time. Is it possible to return 2 associative arrays with the same key to JQuery? How do I append the error messages to the same div? Everything works fine except how the error messages are displayed.
Note: This program is a JQuery Mobile Application
PHP code
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$feedback = $_POST['feedback'];
$errors = array();
if (filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($email)) {
//Do something
} else {
$errors = "Invalid email.";
echo json_encode(array("error" => "{$errors}"));
}
if (!empty($feedback)) {
//Do something
} else {
$errors = "Feeback field can not be empty.";
echo json_encode(array("error" => "{$errors}"));
}
if (empty($errors)) {
//Database Insertion here
echo json_encode(array("success" => "Feedback submission successful."));
}
}
JQuery Code
$(function() {
$('#contact_form').bind('submit', function(event) {
event.preventDefault();
$.post('includes/form.php', $(this).serialize(), function(data) {
if (data.error) {
$('.error').slideDown(100).html(data.error);
} else {
$('.error').hide();
$('.success').slideDown(100).html(data.success);
}
}, "json");
});
});
HTML Form Code
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" id="contact_form" data-ajax="false">
<label for="email">Email:</label>
<input type="text" name="email" id="email" placeholder="Email">
<label for="feedback">Feedback:</label>
<textarea type="text" name="feedback" id="feedback" placeholder="Feedback"></textarea>
<input type="submit" name="submit" value="Submit Feedback" class="submit">
</form>
Thank you in advance.
Edit: I feel so silly. I forgot to append the error messages in the php script haha. Thank you to all who answered.