2016-12-09 132 views
0

我正在嘗試構建自己的WordPress主題,它似乎可行,但我遇到了電子郵件表單的問題。當我在適應WordPress之前使用它的代碼工作,但現在沒有。未找到Ajax調用php,404錯誤

$(function() { 
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({ 
    preventSubmit: true, 
    submitError: function($form, event, errors) { 
     // additional error messages or events 
    }, 
    submitSuccess: function($form, event) { 
     // Prevent spam click and default submit behaviour 
     $("#btnSubmit").attr("disabled", true); 
     event.preventDefault(); 
     console.log ('1'); 

     // get values from FORM 
     var name = $("input#name").val(); 
     var email = $("input#email").val(); 
     var phone = $("input#phone").val(); 
     var message = $("textarea#message").val(); 
     var firstName = name; // For Success/Failure Message 

     // Check for white space in name for Success/Fail message 
     if (firstName.indexOf(' ') >= 0) { 
      firstName = name.split(' ').slice(0, -1).join(' '); 
      console.log ('2'); 
     } 

     $.ajax({ 
      url: "./mail/contact_me.php", 
      type: "POST", 
      data: { 
       name: name, 
       phone: phone, 
       email: email, 
       message: message 
      }, 
      cache: false, 
      success: function() { 
       // Enable button & show success message 
       console.log ('3'); 

       $("#btnSubmit").attr("disabled", false); 
       $('#success').html("<div class='alert alert-success'>"); 
       $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") 
        .append("</button>"); 
       $('#success > .alert-success') 
        .append("<strong>Your message has been sent. </strong>"); 
       $('#success > .alert-success') 
        .append('</div>'); 

JavaScript文件是在這條航線:domain/wp-content/themes/federo/js/contact_me.js

而且PHP文件是在這裏:domain/wp-content/themes/federo/mail/contact_me.php

+0

它只是沒有找到頁面。你應該試試這個:'../ mail/contact_me.php' – Jai

+0

我想錯了。我的意思是:如果您將URL替換爲:'「/wp-content/themes/federo/mail/contact_me.php」' –

+0

非常感謝!!!它的工作,我覺得像一個愚蠢的,但你的幫助已經很大 – Federo

回答

0

試圖改變

url: "./mail/contact_me.php", 

成絕對路徑

url: "http://domain/wp-content/themes/federo/mail/contact_me.php", 
+0

謝謝,馬格努斯,你是對的 –

+0

是的,它的工作原理,我覺得有點愚蠢,但我真的讚賞你的幫助! – Federo

1

即使@魯斯蘭 - nigmatulin答案會的工作,這是更好地傳遞URL(和你需要的任何其他東西)wp_localize_script功能,像這樣:

wp_localize_script('ajax-script', 'ajax_object', array('ajax_url' => get_template_directory_uri() . '/mail/contact_me.php'); 

在這個例子中:
- ajax-script是手柄你與wp_enqueue_script
使用 - ajax_object是對象,將提供給您的腳本的名稱
- 3 paramater是你想值數組傳遞

然後讓你的JS中的,你只需要做ajax_object.ajax_url。在這種情況下(假設federo是你當前的主題),ajax_object.ajax_url將是http://domain/wp-content/themes/federo/mail/contact_me.php

+0

Wp給你的功能,所以使用它的全部潛力,所以在將來你不需要改變你的js中的所有URL。只需更改函數中的URL即可。 –

+0

許多人都非常感謝您的擔憂,在這一刻我嘗試了以前的解決方案並努力工作,所以我會嘗試着改進我在這個主題中的技能。非常感謝你的幫助,我真的讚賞它 – Federo