Hannes De Baere
Hannes De Baere

Reputation: 7

Jquery clear my textfields after submit

I wrote some jquery code to send my data to a php file that puts the data into my database without reloading the page(that works), but after that I want to clear the input fields, there seems to be a problem, but I can't find it...

$(document).ready(function() {
    $('.wrapper').find('input[type="submit"]').on('click', function(e){
        e.preventDefault();
        submitGegevens();
    });
});
function submitGegevens(){
    $.ajax({
      type: "POST",
      url: "addComment.php",
      data: {
        'name' : $('input[name="name"]').val(),
        'email' : $('input[name="email"]').val(),
        'phone' : $('input[name="phone"]').val(),
        'comment' : $('textarea[name="comment"]').val(),
      }
    }).done(function(data){
        $('.error').html(data);
    });
    if ($(data).is(":empty")){
        $('input[name="name"]').val(''),
        $('input[name="email"]').val(''),
        $('input[name="phone"]').val(''),
        $('textarea[name="comment"]').val(''),
    };
}

This is the php code:

<?php
include "functies.php";
//PREG_MATCH:
function controleerEmail($email){
    return(filter_var($email, FILTER_VALIDATE_EMAIL));
}
$message = '';
    if(empty($_POST['email']) or !controleerEmail($_POST['email'])){
    $message .= 'Please enter a valid email address.<br>';
}
echo $message;

if(empty($message)){
    klantToevoegen($_POST['name'],$_POST['phone'],$_POST['email'],$_POST['comment']);
}

?>

Upvotes: 0

Views: 42

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

The data is available only in the done callback, so you need to test whether it is empty in the callback itself

function submitGegevens() {
    $.ajax({
        type: "POST",
        url: "addComment.php",
        data: {
            'name': $('input[name="name"]').val(),
                'email': $('input[name="email"]').val(),
                'phone': $('input[name="phone"]').val(),
                'comment': $('textarea[name="comment"]').val(),
        }
    }).done(function (data) {
        $('.error').html(data);
        if ($(data.trim()).is(":empty")) {
            $('input[name="name"]').val(''),
            $('input[name="email"]').val(''),
            $('input[name="phone"]').val(''),
            $('textarea[name="comment"]').val(''),
        };
    });
}

Upvotes: 1

Related Questions