2016-04-22 127 views
1

我在Wordpress模板中製作了一個表單,該表單進行了某些計算並在模態引導程序中顯示結果。如何在不刷新頁面的情況下發送表單

HTML:

//FORM 
<form method="post" id="myForm"> 
<span>Name</span><br><input type="text" name="name" id="name" required> 

<span>Email</span><br> 
<input type="email" name="email" id="email" required> 

<span>Altura</span><br> 
<input type="number" name="altura" id="altura" required> 

<span>Peso</span><br> 
<input type="number" name="peso" id="peso" required> 
    <br><br> 

<button type="submit" id="enviar" onclick="calcularIMC();">Enviar</button> 

//MODAL 
<div class="modal fade" id="ajax-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> 
    <div class="modal-dialog" role="document"> 
    <div class="modal-content"> 
     <div class="modal-body"> 
     <div id="corpo_modal"> 
        <p> ALL FIELDS </p> 
     </div> 
     </div> 
     <div class="modal-footer"> 
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
     </div> 
    </div> 
    </div> 
</div> 

JAVASCRIPT:

function calcularIMC(){ 
var nome = document.getElementById("nome").value; 
var email = document.getElementById("email").value; 
var estilo = document.getElementById("estilo").value; 
var experiencia = document.getElementById("experiencia").value; 
var altura = document.getElementById("altura").value; 
var peso = document.getElementById("peso").value; 
var resultado = 5; 

var corpo = document.getElementById("corpo_modal"); 


var imc = 0; 
if(altura >0 && peso >0){ 
    imc = peso/(altura * altura); 
} 


if(estilo == "Surf"){    
     if((imc<=25) && (resultado == 5)){   
      corpo.innerHTML = '<img src="1.png" style="width: 150px; height:150px">'; 
     } 
     else{   
     corpo.innerHTML = '<img src="2.png" style="width: 150px; height:150px">'; 
      } 
    } 


    else if(estilo == "SUP"){ 

     if((experiencia >= 3) && (imc <=29)){ 
      corpo.innerHTML = '<img src="3.png" style="width: 150px; height:150px">'; 
     } else{ 
      corpo.innerHTML = '<img src="4.png" style="width: 150px; height:150px">'; 
     }      
    } 
} 

的問題是,當我發送的形式,它更新頁面和不顯示模式。
經過一番研究,我發現要解決這個問題,我需要使用Ajax - jQuery.ajax。

我發現這個代碼:

$(function() { 
    $('form#myForm').on('submit', function(e) { 
     $.post('', $(this).serialize(), function (data) { 
      // This is executed when the call to mail.php was succesful. 
      // 'data' contains the response from the request 
     }).error(function() { 
      // This is executed when the call to mail.php failed. 
     }); 
     e.preventDefault(); 
    }); 
}); 

當我創建一個單獨的頁面形式,根本不把在WordPress模板,它的工作原理。但是當我將代碼放在wordpress模板中時,它會在3秒後更新頁面。

我還發現,我可以在jquery,功能$.ajax();使用原生功能ajax和自己的內部我用標籤,如urltypedata等。我是阿賈克斯的初學者,我迷失在如何做到這一點。

爲什麼功能e.preventDefaul();不工作,當我把wordpress模板?有可能讓它在wordpress模板中工作?

我如何使用$.ajax()來解決這個問題?

我想發送表單而不刷新頁面!

+0

有你包括jQuery庫? –

+0

是啊!肯定是的。只是發佈沒有找到必要 – Zkk

回答

1

拿你javsacript控制檯中查找錯誤F12在Web瀏覽器

您可能會看到undefined variable "$"或類似的錯誤消息。

爲避免與其他javascript庫衝突WordPress默認調用jQuery noConflict

最簡單的解決方法是換你的代碼中的iife傳入jQuery對象,並重新定義爲$

(function($){ 

    console.log($); 
    //your code 

})(jQuery) 

更多信息

的WordPress具有處理AJAX一個特殊的URL請求並且期望動作字段在後端應該被調用的函數:

(function($){ 
    $(function() { 
     $('form#myForm').on('submit', function(e) { 
      var data = $(this).serialize(); 
      data += '&action=my_action' 
      $.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (response) { 
      console.log(response)    

     }).error(function() { 
      console.log('XHR error') 
      }); 
      e.preventDefault(); 
     }); 
    }); 
})(jQuery) 

你會再增加一個處理函數到你的functions.php文件:

add_action('wp_ajax_my_action', 'my_action_callback'); 
add_action('wp_ajax_nopriv_my_action', 'my_action_callback'); 

function my_action_callback() { 
    global $wpdb; // this is how you get access to the database 

    $whatever = intval($_POST['whatever']); 

    $whatever += 10; 

     echo $whatever; 

    wp_die(); // this is required to terminate immediately and return a proper response 
} 

進一步閱讀

https://codex.wordpress.org/AJAX_in_Plugins

How do I return the response from an asynchronous call?

+0

的確,這是與JQuery文件的衝突。感謝您的詳細解釋。一個問題,使用事件'e.preventDefault()'來阻止頁面刷新被認爲是不好的做法? – Zkk

+0

'e.preventDefault()'絕對是防止表單提交的正確方法 – andrew

+0

除了e'.preventDefault()'我也可以通過'$ .ajax()'做到這一點。 – Zkk

1

在wordpress中發佈數據時,您應該在您的wordpress主題中處理functions.php文件中的請求。

並與WordPress的工作時,你不應該使用美元符號與取代它的​​jQuery這將讓你發佈這樣的代碼:

jQuery(function() { 
    jQuery('form#myForm').on('submit', function(e) { 
     $.post('', jQuery(this).serialize(), function (data) { 
     }).error(function() { 
      // This is executed when the call to mail.php failed. 
     }); 
     e.preventDefault(); 
    }); 
}); 

的functions.php

add_action('wp_ajax_[action]', 'my_function'); 

function my_function() { 
    var_dump($_POST); 
} 

The [action]佔位符需要替換爲動作ma從Ajax調用tched例如說「my_action」

var data = { 
    action: 'my_action', 
    form: jQuery(this).serialize() 
} 

jQuery(function() { 
    jQuery('form#myForm').on('submit', function(e) { 
     $.post('', data, function(data) { 
      }).error(function() { 
     }); 
     e.preventDefault(); 
    }); 
}); 
0

ZKK, 你其實並不需要提交什麼...
2快速解決方案在這裏:

  1. 您的輸入類型更改爲button;或
  2. 以下內容添加到您的JavaScript代碼來

var meuFormulario = document.getElementById("myForm"); 
meuFormulatio.onsubmit = function(event){ 
    event.preventDefault(); 
} 

這將取消您的提交行動,僅運行JavaScript函數來計算Índice de Massa Corporea (IMC)需要;)

+0

我將數據發送到數據庫。所以我需要一個'submit' – Zkk

相關問題