简体   繁体   English

如何发送表单而不刷新页面

[英]How to send a form without refreshing the page

I make a form in Wordpress Template that makes certain calculation and displays the result in a modal Bootstrap. 我在Wordpress模板中制作了一个表格,该表格进行了一定的计算并将结果显示在模态Bootstrap中。

HTML: 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: 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">';
        }                       
     }
}

The problem is that when I send the form, it updates the page and does not display the modal. 问题是,当我发送表单时,它会更新页面而不显示模式。
After some research, I found that to solve this problem I will need to use Ajax - jQuery.ajax. 经过研究,我发现要解决此问题,我将需要使用Ajax-jQuery.ajax。

I found this code: 我发现此代码:

$(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();
  });
});

When I create a form in a SEPARATE page without putting in wordpress template, it works. 当我在SEPARATE页面中创建表单而不放入wordpress模板时,它可以工作。 But when I put the code in wordpress template it updates the page after 3 seconds. 但是,当我将代码放入wordpress模板时,它将在3秒后更新页面。

I also discovered that I can use a native function ajax in jquery , the function $.ajax(); 我还发现我可以在jquery使用本机函数ajax ,即$.ajax();函数$.ajax(); and inside of oneself I use tags like url , type , data and so on. 在自己内部,我使用urltypedata等标签。 I'm a beginner in Ajax and I'm lost on how to do this. 我是Ajax的初学者,但我对如何执行此操作一无所知。

Why the function e.preventDefaul(); 为什么使用函数e.preventDefaul(); not works when I put in wordpress template?? 当我放入WordPress模板时不起作用? It's possible make it work in wordpress template? 有可能使其在Wordpress模板中工作吗?

or 要么

How I can use the $.ajax() to solve this problem?? 我如何使用$.ajax()解决此问题?

I want send the form without refresh the page! 我要发送表单而不刷新页面!

When posting data in wordpress you should handle the request in the functions.php file in your wordpress theme. 在wordpress中发布数据时,您应该在wordpress主题中的functions.php文件中处理请求。

And you shouldn't use the dollar sign when working with wordpress replace it with jQuery which would make the code you posted like this: 而且在使用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 的functions.php

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

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

The [action] placeholder needs to be replaced with the action matched from your ajax call, say for example 'my_action' [action]占位符需要替换为ajax调用中匹配的action,例如“ 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();
    });
});

Take a look in your javsacript console for errors f12 in your web browser 在您的javsacript控制台中查看网络浏览器中的错误f12

You'll likely see undefined variable "$" or similar error message. 您可能会看到undefined variable "$"或类似的错误消息。

To avoid conflict with other javascript libraries WordPress invokes jQuery noConflict by default. 为了避免与其他JavaScript库发生冲突,WordPress默认会调用jQuery noConflict

The easiest solution is to wrap your code inside an iife passing in the jQuery object and redefining it as $ 最简单的解决方案是将代码包装在传入jQuery对象的iife中,并将其重新定义为$

(function($){

   console.log($);
   //your code

})(jQuery)

Further information 更多信息

Wordpress has a special url for handling ajax requests and expects an action field for which function at the backend should be called: Wordpress有一个用于处理ajax请求的特殊URL,并且期望一个应在后端调用其功能的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)

You would then add a handler function into your functions.php file: 然后,您可以将处理程序函数添加到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
}

Further reading 进一步阅读

https://codex.wordpress.org/AJAX_in_Plugins https://codex.wordpress.org/AJAX_in_Plugins

How do I return the response from an asynchronous call? 如何从异步调用返回响应?

Zkk, You actually don't need to submit anything... Zkk,您实际上不需要提交任何内容...
2 quick solutions here: 这里有2个快速解决方案:

  1. Change your input type to button ; 将输入类型更改为button or 要么
  2. Add the following to your javascript tag 将以下内容添加到您的javascript标记中

:

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

This will cancel your submit action and only run your javascript function to calculate the Índice de Massa Corporea (IMC) you need ;) 这将取消您的提交操作,并且仅运行您的JavaScript函数来计算您需要的“ Índice de Massa Corporea (IMC) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM