jeudi 8 octobre 2015

WordPress Validate Before Submitting Form

I decided to build a WordPress contact form plugin - everything is working fine - for example once the plugin is activated the table is created is the database, the section for the contact form responses is added to the WP admin area. The forms are submitting without refreshing the page and displaying a success / error message when sent / failed to send and saving to the database each time. However I can't get validation to work -

I came across the following jquery validation plugin - http://ift.tt/15JYAzL - could someone tell me if this plugin could be used with my code to validate the forms data and then only submit when all fields are filled in correctly. I have posted my code below.

PLUGIN CODE

<?php
/*
Plugin Name: Contact Us Form Plugin
Plugin URI: iphonerepair.ie
Description: Contact us form with validaton - sends email and posts responses to database and WP dashboard. 
Version: 1.0
Author URI: jms-design.co.uk
*/

if(!defined('WPINC'))
{
die;
}

// create table at plugin activition
register_activation_hook( __FILE__, 'jms_create_db' );
function jms_create_db() 
{
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table_name=$wpdb->prefix.'contactusform';
        $sql="CREATE TABLE $table_name(
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                time datetime DEFAULT NULL,
                name varchar(50) DEFAULT NULL,
        telno int(20) DEFAULT NULL,
                email varchar(75) DEFAULT NULL,
        town varchar(75) DEFAULT NULL,
        device varchar(75) DEFAULT NULL,
                message text,
                UNIQUE KEY id (id)
                ) $charset_collate;";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta( $sql );
}

//adding plugin to admin menu
add_action('admin_menu', 'jms_menu');
function jms_menu() 
{
 add_menu_page(__('Contact Form','jms'), __('Contact Form','jms'),
         'administrator', 'jms-contact-form', 'jms_settings_page', 'dashicons-email');
        function jms_settings_page() 
         {
                global $wpdb;
                $table_name=$wpdb->prefix.'contactusform';
                $client_msg = $wpdb->get_results( 
                        "
                        SELECT *
                        FROM $table_name
                        "
                );
                require_once(plugin_dir_path(__FILE__).'settings-page.php');
         }
         
}

function cf_jms()
{
 ob_start();
 require_once(plugin_dir_path(__FILE__).'form.php');
 return ob_get_clean();
}
add_shortcode( 'jms_contact_form', 'cf_jms' );

//if you want to have both logged in and not logged in users submitting, you have to add both actions!
add_action( 'admin_post_add_foobar', 'jms_admin_add_foobar' );
add_action( 'admin_post_nopriv_add_foobar', 'jms_admin_add_foobar' );
function jms_admin_add_foobar() {
    global $wpdb;
    $data = array(
        'time'  => current_time('mysql'),
        'name'  => sanitize_text_field( $_POST['name']),
        'telno'  => sanitize_text_field( $_POST['telno']),
        'email' => isset( $_POST['email'] ) ? sanitize_email( $_POST['email']) : null,
        'town'  => sanitize_text_field( $_POST['town']),
        'device'  => sanitize_text_field( $_POST['device']),
        'message'   => sanitize_text_field( $_POST['message'])
    );

    $table_name = $wpdb->prefix.'starkod';
    $headers = array( 'Content-Type: text/html; charset=UTF-8' );
    // send Email for admin
    wp_mail(
        get_option( 'admin_email' ),
        'Instant Qoute/Callback Form',
        'Time : ' . $data['time'] .
        'Name : ' . $data['name'] .
        'Tel No : ' . $data['telno'] .
        'Email : ' . $data['email'] .
        'Town : ' . $data['town'] .
        'Device : ' . $data['device'] .
        ' The message: ' . $data['message'],         
        $headers
    );

    if ( $wpdb->insert( $table_name, $data ) ) {
        $_SESSION['message'] = "Your Message received , thanks ";
    } else {
        $_SESSION['message'] = "there's problem try again please";
    }
    //redirect back to where user was comming
    wp_redirect( $_SERVER['HTTP_REFERER'] );
    //request handlers should die() when they complete their task
}

?>
<?php
/*
Plugin Name: Contact Us Form Plugin
Plugin URI: iphonerepair.ie
Description: Contact us form with validaton - sends email and posts responses to database and WP dashboard. 
Version: 1.0
Author URI: jms-design.co.uk
*/

if(!defined('WPINC'))
{
die;
}

// create table at plugin activition
register_activation_hook( __FILE__, 'jms_create_db' );
function jms_create_db() 
{
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table_name=$wpdb->prefix.'contactusform';
        $sql="CREATE TABLE $table_name(
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                time datetime DEFAULT NULL,
                name varchar(50) DEFAULT NULL,
        telno int(20) DEFAULT NULL,
                email varchar(75) DEFAULT NULL,
        town varchar(75) DEFAULT NULL,
        device varchar(75) DEFAULT NULL,
                message text,
                UNIQUE KEY id (id)
                ) $charset_collate;";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta( $sql );
}

//adding plugin to admin menu
add_action('admin_menu', 'jms_menu');
function jms_menu() 
{
 add_menu_page(__('Contact Form','jms'), __('Contact Form','jms'),
         'administrator', 'jms-contact-form', 'jms_settings_page', 'dashicons-email');
        function jms_settings_page() 
         {
                global $wpdb;
                $table_name=$wpdb->prefix.'contactusform';
                $client_msg = $wpdb->get_results( 
                        "
                        SELECT *
                        FROM $table_name
                        "
                );
                require_once(plugin_dir_path(__FILE__).'settings-page.php');
         }
         
}

function cf_jms()
{
 ob_start();
 require_once(plugin_dir_path(__FILE__).'form.php');
 return ob_get_clean();
}
add_shortcode( 'jms_contact_form', 'cf_jms' );

//if you want to have both logged in and not logged in users submitting, you have to add both actions!
add_action( 'admin_post_add_foobar', 'jms_admin_add_foobar' );
add_action( 'admin_post_nopriv_add_foobar', 'jms_admin_add_foobar' );
function jms_admin_add_foobar() {
    global $wpdb;
    $data = array(
        'time'  => current_time('mysql'),
        'name'  => sanitize_text_field( $_POST['name']),
        'telno'  => sanitize_text_field( $_POST['telno']),
        'email' => isset( $_POST['email'] ) ? sanitize_email( $_POST['email']) : null,
        'town'  => sanitize_text_field( $_POST['town']),
        'device'  => sanitize_text_field( $_POST['device']),
        'message'   => sanitize_text_field( $_POST['message'])
    );

    $table_name = $wpdb->prefix.'starkod';
    $headers = array( 'Content-Type: text/html; charset=UTF-8' );
    // send Email for admin
    wp_mail(
        get_option( 'admin_email' ),
        'Instant Qoute/Callback Form',
        'Time : ' . $data['time'] .
        'Name : ' . $data['name'] .
        'Tel No : ' . $data['telno'] .
        'Email : ' . $data['email'] .
        'Town : ' . $data['town'] .
        'Device : ' . $data['device'] .
        ' The message: ' . $data['message'],         
        $headers
    );

    if ( $wpdb->insert( $table_name, $data ) ) {
        $_SESSION['message'] = "Your Message received , thanks ";
    } else {
        $_SESSION['message'] = "there's problem try again please";
    }
    //redirect back to where user was comming
    wp_redirect( $_SERVER['HTTP_REFERER'] );
    //request handlers should die() when they complete their task
}

?>

FORM CODE

<form name='message' id='message' class="contactusform" enctype="multipart/form-data" action="<?=admin_url()?>admin-post.php">
<?php
 if(isset($_SESSION['message']))
 {
 echo $_SESSION['message'];
 unset($_SESSION['message']);
 }
 ?>
     <input type="hidden" name="action" value="add_foobar">
     <input type="hidden" name="data" value="foobarid">
     <label>Full Name:</label><input type="text" name="name" value="" required="">
     <label>Phone Number:</label><input type"=text" name="telno" id="telno">
     <label>Email Address:</label><input type="email" name="email" value="" required="">
     <label>Town:</label><input type"=text" name="town" value="" required="">
     <label>Device:</label><select name="device" value="" required="">
        <option selected="selected" value=""></option><option value="Not Sure">Not Sure</option><option selected="selected" value=""></option><option value="iPhone 3G">iPhone 3G</option><option value="iPhone 3GS">iPhone 3GS</option><option value="iPhone 4G">iPhone 4G</option><option value="iPhone 4S">iPhone 4S</option><option value="iPhone 5">iPhone 5</option><option value="iPhone 5C">iPhone 5C</option><option value="iPhone 5S">iPhone 5S</option><option value="iPhone 6">iPhone 6</option><option value="iPhone 6 Plus">iPhone 6 Plus</option><option selected="selected" value=""></option><option value="MacBook">MacBook</option><option value="MacBook Pro">MacBook Pro</option><option value="MacBook Air">MacBook Air</option><option selected="selected" value=""></option><option value="iMac">iMac</option><option selected="selected" value=""></option><option value="iPad 1">iPad 1</option><option value="iPad 2">iPad 2</option><option value="iPad 3">iPad 3</option><option value="iPad 4">iPad 4</option><option value="iPad Air">iPad Air</option><option value="iPad Air 2">iPad Air 2</option><option value="iPad Mini 1">iPad Mini 1</option><option value="iPad Mini 2">iPad Mini 2</option><option value="iPad Mini 3">iPad Mini 3</option><option selected="selected" value=""></option><option value="iPod Classic">iPod Classic</option><option value="iPod Mini">iPod Mini</option><option value="iPod Nano">iPod Nano</option><option value="iPod Shuffle">iPod Shuffle</option><option value="iPod Touch">iPod Touch</option>
    </select>
    <label>Message:</label><textarea name="message" cols="30" rows="4" value="" required=""></textarea>
</form>
<input class="submit2" type='button' id='submit2' value='Send Message' />
<div id='simple-msg'></div>

SCRIPT TO SUBMIT FORM

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

    // grab the submits button ID. do not use <input type="submit"> inside the form. Use a button instead outside the form.
    $("#submit2").click(function()
    {
        // grab the forms ID
        $("#message").submit(function(e)
        {
            // add a loading image in place of your returning outcome
            $("#simple-msg").html("sending...");

            // serialize/combine all submitted fields into an array
            var postData = $(this).serializeArray();

            // set url based of action
            var formURL = $(this).attr("action");

            // set ajax parameters
            $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR) 
                {
                    $("#simple-msg").html('<p>Thanks for your request - we will be in touch soon!</p>');

                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                    $("#simple-msg").html('<p>Message failed to send. Please try again!</p>');
                }
            });
            e.preventDefault(); //STOP default action
            e.unbind();
        });

        $("#message").submit(); //SUBMIT FORM
    });

});
</script>

If someone could help me resolve this - it would be much appreciated. Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire