联系表单与AJAX无法在Wordpress中工作

时间:2016-03-26 15:22:18

标签: javascript php jquery ajax wordpress

我在Wordpress网站上工作,并且我正在尝试创建一个表单(带有ajax调用),该表单出现在每个产品页面上。我已经在其他服务器上尝试过,工作得非常好,但是当我将我的代码集成到Wordpress页面时却无法正常工作。我正在使用Woocomerce,因此我尝试修改的php文件是" content-single-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>
&#13;
&#13;
&#13;

PHP代码是

&#13;
&#13;
<?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);
	}
}
?>
&#13;
&#13;
&#13;

我对Wordpress没那么熟悉。我想,我必须以某种方式适应它。这实际上是我的问题。谢谢!

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找这个: 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'); ?>'
};

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

然后在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);
  }
}