Wordpress:Ajax无法插入,查询和结果数据 [英] Wordpress: Ajax not working to insert, query and result data
问题描述
在我的网站上,通过表单
我在数据库中发送/注册相同的信息,执行 SELECT
/ query并返回它!返回保存在数据库中的最后一个表,只是刚刚在表单上输入的用户(以及来自数据库的更多信息)。
On my site, through a form
I send/register same information in database, do a SELECT
/query and return it! Return the last table saved in database, just that user just entered on the form (along with some more information coming from the database).
我想如何显示这些值来自数据库的 modal bootstrap
,页面必须不提供刷新。为此,我按如下方式插入 AJAX
:
How I want to display these values coming from databse in a modal bootstrap
it's necessary that the page doesn't give the refresh. For this, I inserted the AJAX
as follows:
$(document).ready(function(){
$('#enviar').click(function(){
$.ajax({
//CALL AJAX IN WORDPRESS
url: 'wp-admin/admin-ajax.php',
type: 'POST',
//INSERT, QUERY AND DISPLAYS TO USER
data: 'action=prancha',
error: function(){
alert('ERRO!!!');
},
//IF OK, DISPLAYS TO USER IN DIV "RESULT"
success: function(data){
$('#result').html(data);
}
});
});
});
在我的functions.php文件中:
In my functions.php file:
function prancha(){
header('Content-Type: text/html; charset=utf-8');
include "../../../wp-config.php";
/* DECLARING THE VARIABLES */
$nome = "";
$email = "";
$estilo = "";
$experiencia = "";
$altura = "";
$peso = "";
// VALIDATION
if(!empty($_POST)){
$nome = $_POST['nome'];
$email = $_POST['email'];
$estilo = $_POST['estilo'];
$experiencia = $_POST['experiencia'];
$altura = $_POST['altura'];
$peso = $_POST['peso'];
cadastra_user($nome, $email, $estilo, $experiencia, $altura, $peso);
}
//INSERT IN DATABASE NAME, EMAIL, ESTILE, EXPERIENCE, HEIGHT AND WEIGHT
function cadastra_user($nome, $email, $estilo, $experiencia, $altura, $peso){
global $wpdb;
$table = 'user';
$data = array(
'nome' => $nome,
'email' => $email,
'estilo' => $estilo,
'exp' => $experiencia,
'altura' => $altura,
'peso' => $peso,
);
$updated = $wpdb->insert( $table, $data );
if ( ! $updated ) {
$wpdb->print_error();
}
}
//CONECT WITH DATABASE TO DO THE SELECT
include "db.php";
function BuscaAlgo($conexao){
// QUERY + INNER JOIN IN DATABASE
$query = "SELECT USU.usuario,
USU.nome,
USU.exp,
USU.altura,
USU.peso,
PRAN.exp_ref,
PRAN.altura_ref,
PRAN.peso_ref,
PRAN.tipo_prancha,
PRAN.tamanho_prancha,
PRAN.meio_prancha,
PRAN.litragem_prancha
FROM DADOS_USUARIO AS USU
INNER JOIN PRANCHA AS PRAN
on USU.exp = PRAN.exp_ref
WHERE USU.altura = PRAN.altura_ref
AND USU.peso = PRAN.peso_ref
ORDER BY USU.usuario DESC LIMIT 1";
$resultado = mysqli_query($conexao,$query);
$retorno = array();
while($experiencia = mysqli_fetch_assoc($resultado)){
$retorno[] = $experiencia;
}
return $resultado;
}
//DISPLAYS THE QUERY TO USER
$resultado = array();
$resultado = BuscaAlgo($conexao);
foreach($resultado as $valor){
echo $valor["usuario"]; print(". . . .");
echo $valor["nome"]; print(". . . .");
echo $valor["exp"]; print(". . . .");
echo $valor["altura"]; print(". . . .");
echo $valor["peso"]; print(". . . .");
print("///////");
echo $valor["tipo_prancha"]; print(". . . .");
echo $valor["tamanho_prancha"]; print(". . . .");
echo $valor["meio_prancha"]; print(". . . .");
echo $valor["litragem_prancha"];
}
die(); //END THE EXECUTION
}
//ADD THE AJAX HOOKS IN WORDPRESS
add_action('wp_ajax_prancha', 'prancha');
add_action('wp_ajax_nopriv_prancha', 'prancha');
代码正在评论,基本上我做了:
The code is commenting, basically I did:
AJAX:
- 在`URL`字段中调用本机Wordpress`admin -ajax.php`。
- 在DATA字段中调用向用户进行注册,查询和显示的函数。
- 在`SUCCESS`字段中,打印`data`的值。
功能:我在数据库中创建注册码,进行查询并使用 echo
打印。
FUNCTIONS: I make the registration code in database, do the query and print with the echo
.
AJAX
正在向我返回错误消息。
The AJAX
is returning me the error message.
我该如何解决这个问题?
How can I solve this?
我做错了什么?
注1:当我插入我的'函数中的代码时,注册代码,查询和
echo'直接显示,在我的 footer.php
中,它可以正常工作。因此,我们可以理解错误甚至不在插入,查询或显示的代码中。
注2:我想在模态boostrap
中显示数据库的返回。起初我只是在屏幕上显示,检查一切正常。之后,我将研究如何将这些数据放入模态
,虽然不是帖子的主要内容,但也欢迎提供如何做的建议。
Note1: When I insert the code that is in my 'functions, the registration code, the query and the
echo' to displays in a direct way, in my footer.php
, it works. Therefore, we can understand that the error is not even in the code of insert,query or displays.
NOTE 2: I want to display the return of database within a modal boostrap
. At first I'm just displaying on the screen, to check that everything is OK. After that I will research on how to put these data into the modal
, although not the main subject of the post, suggestions for how to do this are also welcome.
推荐答案
您的代码中存在一些错误,但您错过了一个非常重要的代码部分,
让它工作, wp_localize_script()
功能:
There is some mistakes in your code, but you have just missed a very important part of code,
to make it work, the wp_localize_script()
function:
add_action('wp_enqueue_scripts', 'meu_ajax_scripts');
meu_ajax_scripts(){
// Register your script (located in a subfolder `js` of your active theme, for example here)
wp_enqueue_script( 'meuscript', get_template_directory_uri().'/js/ajax_script.js', array('jquery'), '1.0', true );
// Making the bridge between php and javascript:
wp_localize_script( 'meuscript', 'meuajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
此代码包含在您主动主题的function.php文件中(或子主题)文件夹...如果是儿童主题,则必须通过替换
。 get_template_directory_uri()
get_stylesheet_directory_uri()
This code goes in the function.php file of your active theme (or child theme) folder… If it is a child theme you have to replace get_template_directory_uri()
by get_stylesheet_directory_uri()
.
如你所见'meuscript'
在两个函数中 wp_enqueue_script()
和 wp_localize_script()
。
As you can see 'meuscript'
is in both functions wp_enqueue_script()
and wp_localize_script()
.
然后你将检索<$ c您的 jQuery
脚本中的$ c>'meuajax'和'ajaxurl'
。
Then you will retrieve 'meuajax'
and 'ajaxurl'
in your jQuery
script.
它们以这种方式组合:
url:meuajax.ajaxurl,
而不是 url :'wp-admin / admin-ajax.php',
。
wp_localize_script()
函数将通过 admin_url('admin-ajax.php')
从你的 jQuery脚本
到你的 php
函数...
They are combined this way: url: meuajax.ajaxurl,
instead of url: 'wp-admin/admin-ajax.php',
.
The wp_localize_script()
function will make the bridge through admin_url( 'admin-ajax.php' )
function from your jQuery script
to your php
function…
(NEW UPDATE - NOVATYUALIZAÇÃO)
关于您的评论,您的回答/问题更新,此 主题 ......
所以这是新更新的jQuery代码(使用与表单数据相关的不同方法)。所有表单数据在通过ajax发送到 prancha()
php函数之前被序列化:
So here is your newly updated jQuery code (with a different approach related to form data). All the form data is serialized before being sent to your prancha()
php function through ajax:
// We use jQuery instead of $. Thanks to Phill Healey (see comments).
// Then we put back the $ shorthand in the function…
jQuery(document).ready(function($){
// Now we can use $ shorthand, avoiding javascript errors (with wordpress).
$('#enviar').submit(function(e){ // Updated
var minhaprancha = $(this).serialize(); // serializing the form data
e.preventDefault(); // preventing form submit normal behavior
//ajax call
$.ajax({
type: 'POST',
action: 'prancha',
url: meuscript.ajaxurl, // the functional url
data: meuscript.minhaprancha, // all the data of the form (serialized)
// Displaying succes message
success: function( data ){
$('#result').html( 'Sucesso : '.data );
// for debugging purpose in browser js console
console.log(data);
},
// Displaying error message
error: function( error ){
$('#result').html( 'Erro! : '. error );
// for debugging purpose in browser js console
console.log(error);
}
});
});
});
将此代码放入活动主题的js子文件夹中的js文件ajax_script.js中(或儿童主题)。
您的html表格(例如),必须与此类似:
Your html form (an example like), has to be some kind of similar as this one:
<form method="post" id="minhaprancha"> // this id is important too (no "action" needed)
<label for="Seu nome">From *</label>
<input name="nome" id="nome" type="text" class="form-control" placeholder="Seu nome" required>
<br />
<label for="Seu email">From *</label>
<input name="email" id="email" type="email" class="form-control" placeholder="Seu email" required>
<br />
<label for="Seu estilo">From *</label>
<input name="estilo" id="estilo" type="text" class="form-control" placeholder="Seu estilo" required>
<br />
<label for="Seu experiencia">From *</label>
<input name="experiencia" id="experiencia" type="text" class="form-control" placeholder="Seu experiencia" required>
<br />
<label for="Seu altura">From *</label>
<input name="altura" id="altura" type="text" class="form-control" placeholder="Seu altura" required>
<br />
<label for="Seu peso">From *</label>
<input name="peso" id="peso" type="text" class="form-control" placeholder="Seu peso" required>
<br />
<?php
// This imput hidden element has the name value of the php function ?>
<input type="hidden" name="action" value="prancha"/>
<input type="submit" id="enviar" name="enviar" value="Enviar">
</form>
<div id="result" class="result"></div>
然后你将检索(如你所知)你的PHP中的数据值:
Then you will retrieve (as you already know) the data values in your php with:
$nome = $_POST['nome'];
$email = $_POST['email'];
$estilo = $_POST['estilo'];
$experiencia = $_POST['experiencia'];
$altura = $_POST['altura'];
$peso = $_POST['peso'];
这次这是一个交钥匙解决方案,它可以工作,一次你已经改编了你的表格。
This time this is a turnkey solution, and it will work, once you have adapted your form to it.
参考文献:
在没有插件的情况下在WordPress网站上使用带有PHP的AJAX
如何获取表单数据w JavaScript / jQuery?
这篇关于Wordpress:Ajax无法插入,查询和结果数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!