0

Seeing as I can't find a solution for my problem I might going about this wrong.

I'm trying to build a form using AJAX that will provide an error response or a successful response upon submitting a form. I am able to get an error response sent to my form, but it is in JSON, which obviously looks bad. For the moment I am using a simplified form with just two requirements: (1) name must be John and (2) the date must be in the future.

Here is my html:

<!DOCTYPE html>
<head>
    <title>AJAX Form</title>
</head>
<body>

    <form action="ajax/contact.php" method="post" class="ajax">
        <div>
            <input type="text" name="name" placeholder="Your name">
        </div>
        <div>
            <input type="text" name="email" placeholder="Your email">
        </div>
        <div>
            <input type="text" placeholder="" class="textinput" name="departuredate" id="departing">
        </div>
        <div>
        <textarea name="message" placeholder="Your message"></textarea>
        </div>
        <input type="submit" value="Send">
    </form>

    <div id="ack"></div>

    <script type="text/javascript" src="js/jquery-1.11.0.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>

    <script>
    $(document).ready(function() {

        $("#departing").datepicker({
            //minDate: 0,
            //maxDate: "+1y",
            dateFormat: "yy-mm-dd",
            defaultDate: new Date(),
        });
    });
    </script>
</body>
</html>

Here is my PHP file:

<?php

$errors = array();
$form_data = array();

$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$date = htmlspecialchars($_POST['departuredate']);
$message = htmlspecialchars($_POST['message']);

if (date('Y-m-d') > $date) {
$errors['date'] = "Date is in the past";
goto end;
}
if ($name != 'John') {
$errors['name'] = "Name is not John";
goto end;
}

end:

if (empty($errors)) {
$form_data['success'] = true;
} else {
$form_data['errors'] = $errors;
}
echo json_encode($form_data);
?>

Here is my AJAX file:

$('form.ajax').on('submit', function() {
var that = $(this),
    url = that.attr('action'),
    type = that.attr('method');

$.ajax({
    url: url,
    type: type,
    data: that.serialize(),
    dataType: 'json',
    cache: false,
    success: 
        function(result) {
        if(!result.success) {
            $('#ack').html(JSON.stringify(result.errors));
            console.log(result.errors);
        } else {
        console.log('Valid date and name entries');
        }
    }
});

return false;
});

Thanks!

  • _“it continues to add additional JSON without removing the previous error response”_ – congrats, you found out what the word “append” _means_. If you don”t want that behavior, use `.html()` instead. And since you are getting an _array_ of error messages in your JSON response, you should _loop_ over that, and handle each error message separately – or _join_ the error messages to _one_ value before putting it into the document. – CBroe May 31 '14 at 21:30
  • Why are you making errors an array when you use goto (yuck!) to ensure it only ever contains one element? Just use a string, and remove `JSON.stringify` from your js funtion. And use `.html(...)` rather than `.append(...)` if you want to overwrite – Steve May 31 '14 at 21:32
  • @CBroe I agree append was stupid (I'm pretty green). @user574632 I did use goto so I only had one error message at a time. Should I not do that? How do I get the error as a string? using `.html(result.errors)` doesn't produce a result... Thanks – user3358753 May 31 '14 at 21:49
  • @user3358753 Use a loop to iterate [the array](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript). – Elliott Frisch May 31 '14 at 23:28
  • @user3358753 in your php remove `$errors = array();` and in the individual blocs use `$errors = "error message here"` then use `.html(result.errors);` in your js – Steve Jun 01 '14 at 00:06

0 Answers0