简体   繁体   中英

Ajax Contact Form in WordPress

I have custom AJAX contact form for my WordPress site. It's working fine with Chrome, IE, Opera, Safari, but it fails in Firefox.

I have this in my function.php

// Contact Form
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );

// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

add_action('wp_ajax_mail_action', 'sending_mail');
add_action('wp_ajax_nopriv_mail_action', 'sending_mail');

function sending_mail(){

    $email = $_POST['email'];
    $comments = $_POST['comments'];
    $name = $_POST['name'];

    $to = get_bloginfo('admin_email');
    $subject = '[Contact Form] From '.$name;
    $message = "Name: $name \n\nEmail: $email \n\nComments: $comments"; 
    $headers = 'From: '.$name. "\r\n" . 'Reply-To: ' . $email;

    mail($to, $subject, $message, $headers);

}

And calling AJAX with :

jQuery("#submit-button").click(function (e) { 

... ... 

var data = {};
data.email = $("#email").val();
data.name = $("#contactName").val();
data.comments = $("#commentsText").val();
data.action = "mail_action";

$.post(MyAjax.ajaxurl, data, onSuccess);

function onSuccess(results){ ... }

}

I actually don't have file ajax.js. I'm confused, it's working in Chrome and other browsers but not in Firefox. Is it because of missing ajax.js?

I tried deleting the line (in functions.php) :

wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );

but then, the form wouldn't work in any browser. I got error Uncaught ReferenceError: MyAjax is not defined

Any help would be appreciated.

you need to this to the end of your sending mail function

die(); // this is required to return a proper result

AJAX in Plugins half way down the page.

Why don't you using a ready solution for this? Try out WordPress Contact Form Slider

It is also works with AJAX and Cross-Browser compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM