AJAX的联系表单在Wordpress中不起作用

Contact form with AJAX not working in Wordpress

本文关键字:Wordpress 不起作用 表单 联系 AJAX      更新时间:2023-09-26

我在Wordpress网站上工作,我正在尝试创建一个表单(使用ajax调用),该表单显示在每个人的产品页面上。我在其他服务器上尝试过,效果很好,但当我将代码集成到Wordpress页面中时,效果不好。我正在使用Woocomerce,所以我试图修改的php文件是"content-sing-product.php"

我的代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
    <script type="text/javascript">
      
    $(document).ready(function() {
        $("#submit_btn").click(function() { 
           
    	    var proceed = true;
            //simple validation at client's end
            //loop through each field and we simply change border color to red for invalid fields		
    		$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
    			$(this).css('border-color',''); 
    			if(!$.trim($(this).val())){ //if this field is empty 
    				$(this).css('border-color','red'); //change border color to red   
    				proceed = false; //set do not proceed flag
    			}
    			//check invalid email
    			var email_reg = /^(['w-'.]+@(['w-]+'.)+['w-]{2,4})?$/; 
    			if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
    				$(this).css('border-color','red'); //change border color to red   
    				proceed = false; //set do not proceed flag				
    			}	
    		});
           
            if(proceed) //everything looks good! proceed...
            {
    			//get input field values data to be sent to server
                post_data = {
    				'user_email'	: $('input[name=email]').val(), 
    				'phone_number'	: $('input[name=telefon]').val(), 
    			};
                //Ajax post data to server
                $.post('*the path to php file*', post_data, function(response){  
    				if(response.type == 'error'){ //load json data from server and output message     
    					output = '<div class="error">'+response.text+'</div>';
    				}else{
    				    output = '<div class="success">'+response.text+'</div>';
    					//reset values in all input fields
    					$("#contact_form  input[required=true], #contact_form textarea[required=true]").val(''); 
    					$("#contact_form #contact_body").slideUp(); //hide form after success
    				}
    				$("#contact_form #contact_results").hide().html(output).slideDown();
                }, 'json');
            }
        });
        
        //reset previously set border colors and hide all message on .keyup()
        $("#contact_form  input[required=true], #contact_form textarea[required=true]").keyup(function() { 
            $(this).css('border-color',''); 
            $("#result").slideUp();
        });
    });	    	
    </script>    	    
    		      	   
    <div style="padding-bottom: 15px; border-bottom: 1px solid #999999;" id="contact_form">
        <div id="contact_results"></div>
        <div id="contact_body">
            <div style="color:#ff0000; font-size:12px;">Title text</div>
    	<p>
    	    <div style="color:#999999; font-size:12px;">Description text</div>
    	</p>
    	<label><span>Phone: </span>
                <input type="text" name="telefon" maxlength="15"  required="true" placeholder="Phone"/>
            </label>
            <label><span>E-mail: </span>
                <input type="email" name="email" required="true" class="input-field" placeholder="E-mail adress"/>
            </label>
            <label>
                <span>&nbsp;</span><input type="submit" id="submit_btn" value="Order now" />
            </label>
        </div>
    </div>

PHP代码是

<?php
if($_POST)
{
	$to_email   	= "email@email.com"; //Recipient email, Replace with own email here
	
	//check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
		
		$output = json_encode(array( //create JSON data
			'type'=>'error', 
			'text' => 'Sorry Request must be Ajax POST'
		));
		die($output); //exit script outputting json data
    } 
	
	//Sanitize input data using PHP filter_var().
	$user_email		= filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
	$phone_number	= filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
	$url			= filter_var($_SERVER['HTTP_REFERER']);
	
	//additional php validation
	if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
		$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
		die($output);
	}
	if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
		$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
		die($output);
	}
	
	//email body
	$subject = "Client nou ! - Telefon: ". $phone_number;
	$message_body = "'r'nNumar de telefon : ". $phone_number."'r'nClientul este interesat de urmatorul produs : ". $url;
	
	//proceed with PHP email.
	$headers = 'From: '.$user_email.'' . "'r'n" .
	'X-Mailer: PHP/' . phpversion();
	
	$send_mail = mail($to_email, $subject, $message_body, $headers);
	
	if(!$send_mail)
	{
		//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
		$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
		die($output);
	}else{
		$output = json_encode(array('type'=>'message', 'text' => '<div style="color:#999999; font-size:12px;">The order was sent. In few moments we will contact you at the phone number <strong>'.$phone_number .'</strong>!</div>'));
		die($output);
	}
}
?>

我对Wordpress没有那么多经验。我想我必须以某种方式适应它。这其实是我的问题。非常感谢。

我想你正在寻找这个:https://codex.wordpress.org/AJAX_in_Plugins

在您的代码中,您需要添加动作后数据:

post_data = {
  'user_email'  : $('input[name=email]').val(), 
  'phone_number'    : $('input[name=telefon]').val(), 
  'action' : 'my_custom_send_mail',
  'nonce' : '<?php wp_create_nonce('mycustom_mail_form_nonce'); ?>'
};

您需要调用<?php echo admin_url('admin-ajax.php'); ?>而不是*the path to php file*

然后在functions.php或my-plugin.php中,您可以调用函数:

add_action( 'wp_ajax_my_custom_send_mail', 'my_custom_send_mail_callback' );
add_action( 'wp_ajax_nopriv_my_custom_send_mail', 'my_custom_send_mail_callback' );
function my_custom_send_mail_callback(){
  if(!check_ajax_referer( 'mycustom_mail_form_nonce', 'nonce' )){
    $output = json_encode(array('type'=>'error', 'text' => 'Something went wrong!'));
    die($output);
  }
  $to_email     = "email@email.com";
  $user_email   = sanitize_email($_POST["user_email"]);
  $phone_number = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
  if(!is_email($user_email)){
    $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
    die($output);
  }
  if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
    $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
    die($output);
  }
  //email body
  $subject = "Client nou ! - Telefon: ". $phone_number;
  $message_body = "'r'nNumar de telefon : ". $phone_number."'r'nClientul este interesat de urmatorul produs : ". $url;
  //proceed with PHP email.
  $headers = 'From: '.$user_email.'' . "'r'n" .
  'X-Mailer: PHP/' . phpversion();
  $send_mail = wp_mail($to_email, $subject, $message_body, $headers);
  if(!$send_mail){
    $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
    die($output);
  }else{
    $output = json_encode(array('type'=>'message', 'text' => '<div style="color:#999999; font-size:12px;">The order was sent. In few moments we will contact you at the phone number <strong>'.$phone_number .'</strong>!</div>'));
    die($output);
  }
}