1

I have a wordpress website. I have made a contact form and it is POSTed by AJAX. Here's the code:

<script type="text/javascript"> 
jQuery(document).ready(function(){
    $("#error_box").hide();
    $('#contact_form').submit(function(e){

        // prevent the form from submitting normally
        e.preventDefault();
        var na=$("#1").val();
        var email2=$("#2").val();
        var subject2 = $("#3").val();
        var message2 = $("#4").val();
   var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;   

        alert(mydata);
            $("#contact_form").css({"opacity":"0.1"});  

        $.ajax ({
            type: 'POST',
            url: $(this).attr.action,  // Relative paths work fine
            data: mydata,
            success: function(){
            $("#contact_form").css({"opacity":"1"});    
            $('#error_box').fadeIn('fast').css({"height": "auto"});
            }
        });

    });
});
    </script>

When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?

[UPDATE]

Here's my contact-form.php file(the action)

<?php   if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
    {

    if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
        echo 'EMPTY ERROR';

    } 
    else
    {
    $name = $_POST['pn2'];
    $email = $_POST['email'];
    $subj = $_POST['subject'];
    $msg = $_POST['msg'];
    $to = "[email protected]";
    $mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
    echo "success";
    mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");

}
}
 ?>

3 Answers 3

1

Form submission using Ajax call Contact Form

<form action="#" id="contactForm" method="post">  
 <input class="require" type="text" placeholder="First Name" name="firstName">    
<span class="fieldError"></span>  
<input class="require" type="text" placeholder="Last Name" name="lastName">  
<span class="fieldError"></span>   
.   
.  
.  
<input type="submit" value="Submit">  
</form>

client side validation with ajax call

jQuery('#contactForm').submit(ajaxSubmit);  
function ajaxSubmit(){  
var newContactForm = jQuery(this).serialize();  
var flag = 0;  
    jQuery('.require', '#contactForm').each(function(){  
        var inputVal = jQuery(this).val();  
if(jQuery.trim(inputVal) === ""){  
            flag = 1;  
            jQuery(this).next().html("Can't be blank");  
            jQuery(this).next().show();  
        }  
        else{  
            jQuery(this).next().hide();  
        }  
    });  
    if(flag){  
        return false;  
    }  
    jQuery.ajax({  
        type:"POST",  
        url: "/wp-admin/admin-ajax.php?action=contactForm",  
        data: newContactForm,  
        success:function(data){  
            jQuery(':input','#contactForm')  
                .not(':button, :submit, :reset, :hidden')  
                .val('')  
                .removeAttr('checked')  
                .removeAttr('selected');  
            jQuery("#feedback").html(data);  
            jQuery("#feedback").fadeOut(10000);  
        },  
        error: function(errorThrown){  
            alert(errorThrown);  
        }  
    });  
    return false;  
}

store form data in db and send mail
add the following code in functions.php

wp_enqueue_script('jquery');  
add_action('wp_ajax_addContactForm', 'addContactForm');  
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');  
function addContactForm(){  
    global $wpdb;  
    $first_name = $_POST['firstName']; $last_name = $_POST['lastName'];  
    $email = $_POST['email'];  
    .  
    .  
    .  
    if($wpdb->insert('table_name',array(  
        'first_name' => $first_name,  
        'last_name' => $last_name,  
        'email' => $email,  
        .  
        .  
        .  
    ))===FALSE){  
        echo "Error";  
    }  
    else {  
        $headers = 'From: xyz <[email protected]>';  
        $subject = "Thank you";  
        $body = "<p>Thank you</p><p>.........</p>";  
        wp_mail( $email, $subject, $body, $headers);  
        echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";  
    }  
    exit;  
}  
Sign up to request clarification or add additional context in comments.

Comments

0

You should use:

      $.ajax ({
            type: 'POST',
            url: $(this).attr.action, 
            data: mydata,
            success: function(response) {  // here you receive response from you serverside 
               $("#contact_form").css({"opacity":"1"});    
               $('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
            }
        });

Your server action url: $(this).attr.action, should return message which be inserted in #error_box

1 Comment

Not working. Now the error box doesn't even appear. Is the response the text echoed in php file? I have added my contact-form.php file. Please tell me if there are any errors in that.
-1

First create form like this

<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
  <fieldset>
    <label><i class="fa fa-file-text-o"></i> Register Form</label>
    <input type="text" name="firstname" placeholder="Username" id="firstname">
    <p id="firstname-error" style="display:none">Firstname Must be Enter</p>
    <input type="email" name="email" placeholder="Email address" id="email">
    <p id="email-error" style="display:none">Email Must Be Enter</p>
    <input type="submit" class="button" id="test" value="Register">
  </fieldset>
</form>

then bind the click and send ajax call

<script type="text/javascript">

 jQuery('#test').on('click', function(e) {
    e.preventDefault();
    var firstname = jQuery('#firstname').val();
    var email = jQuery('#email').val();
    if (firstname == "") {
        jQuery('#firstname-error').show();
        return false;
    } else {
        jQuery('#firstname-error').hide();
    }
    if (email == "") {
        jQuery('#email-error').show();
        return false;
    } else {
        jQuery('#email-error').hide();
    }
    jQuery.ajax({
        type: "POST",
        dataType: 'json',
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: {
        action: "test", // redirect function in function.php
        firstname: firstname,
        email: email
        },
        success: function(results) {
        //console.log(results);
        if (results == "1") {
            jQuery('.register-message').text("Email already exist");
        } else {
            jQuery('.register-message').text("Register successfu");
        }

        },
        error: function(results) {}
    });
    });
 </script>

In function.php add the below code to insert data in table

 <?php
     // 

     add_action('wp_ajax_test', 'test', 0);
     add_action('wp_ajax_nopriv_test', 'test');
     function test()
     {
         $firstname = stripcslashes($_POST['firstname']);
         $email = stripcslashes($_POST['email']);

         global $wpdb;
         $q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
         $res = $wpdb->get_results($q);
         if (count($res) > 0) {
             echo "1";
         } else {
             $user_data = array(
                 'firstname' => $firstname,
                 'email' => $email
             );
             $tablename = $wpdb->prefix . 'test';
             $user_id = $wpdb->insert($tablename, $user_data);
             echo "0";
         }
         die;
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.