Quantcast
Channel: Question and Answer » json
Viewing all articles
Browse latest Browse all 148

Ajax contact form returnig 0

$
0
0

I have read through a lot of responses on this site and am unable to find the issue with my code.

The form is :

<?php while (have_posts()) : the_post()?>
        <form  method='post'  id="dav-international" >
            <label for="dav-address">Address:</label><input type="text" name="dav-address" id="dav-address"/>
            <button type="submit" id="submit">Submit</button>
            </form>
<?php endwhile;?>

The functions are in function.php ( home-page is already enqueued ):

    add_action('wp_enqueue_scripts', 'dav_script');
    function dav_script(){
        if (is_front_page()){
            $dav_nonce = wp_create_nonce('contact_form');
            wp_localize_script('home-page', 'ajaxObj', array(
                    'ajaxurl' => admin_url('admin-ajax.php'),
                    'nonce' => $dav_nonce,
            ));
        }
    }




    add_action('wp_ajax_nopriv_dav_validation', 'dav_form_validation');
    add_action('wp_ajax_dav_validation', 'dav_form_validation');


function dav_form_validation(){
    global $wpdb;
    if ($_SERVER["REQUEST_METHOD"] == 'POST'){
    check_ajax_referer('contact_form');
    $dav_address = sanitize_text_field($_POST['info']);

    $dav_ajax_data = array();
        $dav_ajax_data['dav-address'] = $dav_address;

    echo json_encode($dav_ajax_data);
    }
    wp_die();
}

and the jQuery is :

var $j = jQuery;
                    $j('#submit').click(function(e){
                        var $j = jQuery;
                        e.preventDefault();
                        if ($j('#dav-address').val().length > 0){
                            var formInfo = $j('form').serialize();
                            var formdata = {
                                action : 'dav_validation',
                                  _ajax_nonce: ajaxObj.nonce,
                                  info : formInfo
                            }
                            $j.ajax({
                                type:'post',
                                url: ajaxObj.ajaxurl,
                                data: formdata,
                                success: function(data){
                                    console.log(data);
                                }
                            })
                        }
                        });

I believe I followed the instructions on WordPress codex properly but the console continues to output 0. I am stuck on this and cannot seem to figure it out.


Viewing all articles
Browse latest Browse all 148

Trending Articles