Wordpress ajax联系表单不返回数据

时间:2012-06-08 12:50:32

标签: wordpress jquery

我正在制作一个WordPress主题,每个帖子都有一个联系表单。联系表单将收集有关访问者的信息并向站点管理员发送邮件。它还会向访问者发送一封电子邮件,其中包含可下载PDF的链接(此代码尚未完成)。

我遇到的问题是处理ajax表单的php函数没有响应。它只返回-1(无属性)。但我得到状态代码200 OK。

我在MAMP Pro OSX和DynDNS上运行开发服务器。

这是我在functions.php中的PHP

function ajax_contact() {

  if(!empty($_POST)) {
  $name = $_POST['name'];
  $company = $_POST['company'];
  $mail = $_POST['mail'];
  $admin_mail = get_bloginfo('admin_email');
  $error = "";
  if(!$name) {
      $error .= "Please tell us your name<br/>";
  }
  if(!$company) {
      $error .= "Please tell us your company<br/>";
  }
  if(!$mail) {
      $error .= "Please tell us your E-Mail address<br/>";
  }

  if(empty($error)) {
      $subject = "New download notification";
      $message = "You've received a new download notification. \n\n
          Name: ".$name."\n
          Company: ".$company."\n
          Mail: ".$mail."\n";

      // Send a mail to the admin with the contact info.    
      $send_mail = wp_mail($admin_mail, $subject, $message);

      // Send mail to visitor with the download link.

      if($send_mail) {
      echo "sent";
      die();
      }

  } else {
      echo "error: " . $error;
      die();
    }
  }
}

add_action('wp_ajax_nopriv_ajax_contact', 'ajax_contact');
add_action('wp_ajax_ajax_contact','ajax_contact');

这是javascript代码

    function sendForm(formId, postId, str)
{

    console.log("formId: " + formId);
    console.log("formId: " + postId);
    console.log("str: " + str);

    $.ajax({
        type: "POST",
        url: "../wp-admin/admin-ajax.php",
        action: "ajax_contact",
        data: str,
        success: function(data) {

            $("#" + formId).ajaxComplete(function(event, request, settings){

            if(data == 'sent') {
                $("#" + formId).find(".success").fadeIn("slow");
                }
                else {
                result = data;
                $("#" + formId).siblings(".success").html(result);
                }
            });

        }
    });


}

这是实际的表单(我在同一页面上有多个表单)

<form name="form-<?php the_ID(); ?>" id="form-<?php the_ID(); ?>"/>
    Name <br/> 
    <input type="text" name="name" value=""/><br />
    Company / Organisation <br/> 
    <input type="text" name="company" value=""/><br />
    Email <br/> 
    <input type="text" name="mail" value=""/><br />

    <input type="hidden" name="postId" value="<?php the_ID(); ?>">

    <input type="submit" value="submit" class="requestbutton" id="requestButton-<?php the_ID(); ?>" rel="<?php the_ID(); ?>"/>
  </form>

编辑:更改了ajax操作名称,问题仍然存在

1 个答案:

答案 0 :(得分:0)

您的AJAX action:应为contact_form而不是ajax_contact