drtwqc3744 2017-09-16 04:38
浏览 57
已采纳

使用ajax提交表单时出错并在wordpress中发送邮件

I am trying submit custom form written in header.php with ajax and send mail to particular email address with submitted data,but getting error of 404 in console, form validation is performs taht means jquery file is loaded but when trying to call ajaxurl to send mail it gives 404 error. I am 100% sure that error is in ajax call or need to make function in function.php for sending mail but can't solve it out, can anyone help me solve out this issue?

Form in header.php

<form id="wp_con_form" method="post">
  <ul class="form-list wp_contact_form_ul cf">
    <li>
      <input type="text" name="name" id="name" placeholder="Name *" class="text-field wp_con_frm_name">
    </li>
    <li>
      <input type="text" name="phone" id="phone" placeholder="Phone *" class="text-field wp_con_frm_phone">
    </li>
    <li>
      <input type="text" name="email" id="email" placeholder="Email *" class="text-field wp_con_frm_email">
    </li>
    <li>
      <input type="text" name="agency" id="agency" placeholder="agency" class="text-field ">
    </li>
    <li class="full">
      <textarea name="message" id="message" placeholder="Message *" class="text-field wp_con_frm_message"></textarea>
    </li>
    <li class="form-button">
      <input type="submit" value="Send" id="wp_con_frm_btn" class="button" />
    </li>
    <div class="wp_cont_form_msg"></div>
  </ul>
</form>

calling jquery file in function.php is

wp_enqueue_style( 'themestyle', get_template_directory_uri() . '/assets/css/style.css',false,'1.1','all' );

wp_localize_script("themestyle","the_ajax_theme", array("ajaxurl_anyName" => admin_url("admin-ajax.php")));

Jquery file for validation and ajax call

var j = jQuery.noConflict();

j(document).ready(function(){
function validateContact(){
        var output = true;
        j('.wp_contact_form_ul li').removeClass('wp_cont_frm_err_msg');

        if(!(j(".wp_con_frm_name").val())){
            j(".wp_con_frm_name").parent().addClass('wp_cont_frm_err_msg');
            output = false;
        }

        if(!(j(".wp_con_frm_phone").val())){
            j(".wp_con_frm_phone").parent().addClass('wp_cont_frm_err_msg');
            output = false;
        }

        if(!j(".wp_con_frm_phone").val().match(/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/))
        {
            j(".wp_con_frm_phone").parent().addClass('wp_cont_frm_err_msg');
            output = false;
        }           

        if(!(j(".wp_con_frm_email").val())){
            j(".wp_con_frm_email").parent().addClass('wp_cont_frm_err_msg');
            output = false;
        }

        if(!j(".wp_con_frm_email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/))
        {
            j(".wp_con_frm_email").parent().addClass('wp_cont_frm_err_msg');
            output = false;
        }           

        if(!(j(".wp_con_frm_message").val())){
            j(".wp_con_frm_message").parent().addClass('wp_cont_frm_err_msg');
            output = false;
        }
        return output;
    }

    /* send contact form data to email */

    function afterSubmit(getobj)
    {
        if(getobj.status)
        {           
            j('#wp_con_form')[0].reset();
            j('#wp_con_form .wp_cont_form_msg').html(getobj.message).slideDown().delay(5000).slideUp();             
        }
        else
        {                               
            j('#wp_con_form .wp_cont_form_msg').html(getobj.message).slideDown().delay(5000).slideUp(5000);                 
        }   
    }   

    j('#wp_con_frm_btn').click(function(){
        var output = validateContact();
        if(output){
            var dataString = j("#wp_con_form").serialize();
            j.ajax({
                type: "POST",
                url: ajaxurl,
                dataType:"json",
                data: dataString,               
            }).always(function(data)
            {           
                afterSubmit(data);
            });
        }
        return false;
    });

});

code for sending mail in function.php

$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$msg = $_POST['message'];
$to      = 'yourname@example.com';

$subject =  'List Qwick';
$message =  'Name: '.$name. "
" .
            'Phone: '.$phone. "
" .
            'Email: '.$email. "
" .
            'Message: '.$msg. "
" .

$headers = "From: ".$email."
" .'X-Mailer: PHP/' . phpversion(); 

if(wp_mail($to, $subject, $message, $headers))
{
    $getMessage = '<p class="success">Your Email Has Been Sent Successfully</p>';           
    echo json_encode(array('status'=>1,'message'=>$getMessage));
}
else 
{   
    $getMessage = '<p class="error">Mail function not working..</p>';           
    echo json_encode(array('status'=>0,'message'=>$getMessage));
}
  • 写回答

3条回答 默认 最新

  • doudeng2025 2017-09-16 04:51
    关注

    When you make the Ajax URL available for JavaScript, you're actually creating an object called the_ajax_theme, and one of its properties is called ajaxurl_anyName and contains your Ajax URL.

    wp_localize_script( 'themestyle', 'the_ajax_theme', array(
        'ajaxurl_anyName' => admin_url( 'admin-ajax.php' )
    ) );
    

    In your Ajax call, you're trying to access the ajaxurl which doesn't exists. To use the value that you're actually defining, you have to use the names you defined in your wp_localize_script(). So, your Ajax call should look like this:

    j('#wp_con_frm_btn').click(function(){
        var output = validateContact();
        if(output){
            var dataString = j("#wp_con_form").serialize();
            j.ajax({
                type: "POST",
                url: the_ajax_theme.ajaxurl_anyName,
                dataType:"json",
                data: dataString,               
            }).always(function(data)
            {           
                afterSubmit(data);
            });
        }
        return false;
    });
    

    I'd recommend to use shorten names like themeSlug.ajaxURL.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密