Form submission using AJAX and handling response i

2019-08-07 08:23发布

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 = "ankushverma61@gmail.com";
    $mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
    echo "success";
    mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");

}
}
 ?>

2条回答
别忘想泡老子
2楼-- · 2019-08-07 09:08

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 <xyz@xyz.com>';  
        $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;  
}  
查看更多
The star\"
3楼-- · 2019-08-07 09:09

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

查看更多
登录 后发表回答