javascript - 如何在不刷新页面的情况下发送表单

标签 javascript php html ajax wordpress

我在 Wordpress 模板中制作了一个表单,该表单进行特定计算并在模态 Bootstrap 中显示结果。

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 等标签。我是 Ajax 的初学者,我不知道如何做到这一点。

Why the function e.preventDefaul(); not works when I put in wordpress template?? It's possible make it work in wordpress template?

How I can use the $.ajax() to solve this problem??

我想在不刷新页面的情况下发送表单!

最佳答案

在您的 javasacript 控制台中查看网络浏览器中的错误 f12

您可能会看到 undefined variable "$" 或类似的错误消息。

为避免与其他 javascript 库发生冲突,WordPress 调用 jQuery noConflict 默认。

最简单的解决方案是将代码包装在 iife 传入 jQuery 对象并将其重新定义为 $

(function($){

   console.log($);
   //your code

})(jQuery)

更多信息

Wordpress 有一个特殊的 url 用于处理 ajax 请求,并且需要一个 action 字段,后端的函数应该被调用:

(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?

关于javascript - 如何在不刷新页面的情况下发送表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36798581/

相关文章:

javascript - 显示消息而不重新加载 html 页面

php - YouTube API v3 PHP-取消订阅?

javascript - 隐藏 div 中 href 的 CSS 样式问题?

javascript - 淡出整个页面,除了纯 Javascript 中的一些元素

javascript - window.history.go(-1) 在 iOS 主屏幕应用程序中不起作用

javascript - 获取标签之间的变量并附加到 URL

php - 我如何在 Laravel 中过滤集合?

php - Laravel 5.2 Session flash 即使使用 web 中间件也不工作

javascript - 从单选按钮创建 slider 选择

css - 多类选择器不起作用