[英]Wordpress: Ajax not working to insert, query and result data
On my site, through a form
I send/register same information in database, do a SELECT
/query and return it! 在我的网站上,通过
form
我在数据库中发送/注册相同的信息,执行SELECT
/ query并返回它! Return the last table saved in database, just that user just entered on the form (along with some more information coming from the database). 返回保存在数据库中的最后一个表,只是该用户刚在表单上输入的(以及来自数据库的更多信息)。
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. 我想如何在
modal bootstrap
显示来自databse的这些值,有必要页面不刷新。 For this, I inserted the AJAX
as follows: 为此,我按如下所示插入了
AJAX
:
$(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);
}
});
});
});
In my functions.php file: 在我的functions.php文件中:
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: AJAX:
FUNCTIONS: I make the registration code in database, do the query and print with the echo
. 功能:我在数据库中注册代码,进行查询并使用
echo
打印。
The AJAX
is returning me the error message. AJAX
我返回错误消息。
How can I solve this? 我该如何解决?
What am I doing wrong? 我究竟做错了什么?
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. 注意1:当我插入“功能
, the registration code, the query and the
回显”中的代码以直接方式显示在我的footer.php
,它可以工作。 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
. 注意2:我想在
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. 之后,我将研究如何将这些数据放入
modal
,尽管这不是帖子的主题,但也欢迎提出建议。
First of all, you should use $wpdb object to access the database in Wordpress, including the select. 首先,您应该使用$ wpdb对象访问Wordpress中的数据库,包括select。 Check the documentation https://codex.wordpress.org/Class_Reference/wpdb
检查文档https://codex.wordpress.org/Class_Reference/wpdb
You didn't specify what kind of error you get, but I think your ajax call definition is wrong, it should be: 您没有指定得到哪种错误,但是我认为您的ajax调用定义是错误的,应该是:
data: {
action : 'prancha'
}
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: 要使其工作,请使用
wp_localize_script()
函数:
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' ) ) );
}
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()
. 此代码位于活动主题(或子主题)文件夹的function.php文件中……如果它是子主题,则必须将
get_template_directory_uri()
替换为get_stylesheet_directory_uri()
。
As you can see 'meuscript'
is in both functions wp_enqueue_script()
and wp_localize_script()
. 如您所见,两个函数
wp_enqueue_script()
和wp_localize_script()
中都wp_enqueue_script()
'meuscript'
。
Then you will retrieve 'meuajax'
and 'ajaxurl'
in your jQuery
script. 然后,您将在
jQuery
脚本中检索'meuajax'
和'ajaxurl'
。
They are combined this way: 它们以这种方式组合:
url: meuajax.ajaxurl,
instead of url: 'wp-admin/admin-ajax.php',
. url: meuajax.ajaxurl,
而不是url: 'wp-admin/admin-ajax.php',
url: meuajax.ajaxurl,
The wp_localize_script()
function will make the bridge through admin_url( 'admin-ajax.php' )
function from your jQuery script
to your php
function… wp_localize_script()
函数将通过admin_url( 'admin-ajax.php' )
函数从jQuery script
到php
函数建立桥梁……
(NEW UPDATE - NOVA ATUALIZAÇÃO) (新更新-NOVAATUALIZAÇÃO)
regarding your comments, your answer/question update, and this thread too… 关于您的评论,您的答案/问题更新以及该主题 ……
So here is your newly updated jQuery code (with a different approach related to form data) . 因此,这是您新近更新的jQuery代码(使用与表单数据相关的另一种方法) 。 All the form data is serialized before being sent to your
prancha()
php function through ajax: 通过ajax发送到您的
prancha()
php函数之前,所有表单数据prancha()
序列化:
// 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);
}
});
});
});
Put this code in a js file ajax_script.js inside a js subfolder of your active theme (or child theme). 将此代码放在活动主题(或子主题)的js子文件夹中的js文件ajax_script.js中。
Your html form (an example like) , has to be some kind of similar as this one: 您的html表单(例如这样的示例)必须与此类似:
<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>
Then you will retrieve (as you already know) the data values in your php with: 然后,您将通过以下方式检索(如您所知)php中的数据值:
$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. 这次,这是一个交钥匙的解决方案,一旦您调整了表格的形式, 它就会起作用 。
References: 参考文献:
Wordpress passing ajax value to a specific page using Wordpress Wordpress使用Wordpress将Ajax值传递到特定页面
Using AJAX With PHP on Your WordPress Site Without a Plugin 在没有插件的情况下在WordPress网站上使用AJAX和PHP
How to use Ajax with your WordPress Plugin or Theme? 如何在WordPress插件或主题中使用Ajax?
How can I get form data with JavaScript/jQuery? 如何使用JavaScript / jQuery获取表单数据?
First, I am grateful for their willingness to help. 首先,我感谢他们愿意提供帮助。
Second, I prefer search more about how to solve my issue before coming here with feedback. 第二,在获得反馈之前,我更喜欢搜索有关如何解决我的问题的更多信息。
The code you sent me, still not working. 您发送给我的代码仍然无法正常工作。 I made some changes and it worked in parts.
我进行了一些更改,并且部分运行。
submit
for click
in my jQuery and I also replaced the type of my button for text
. click
submit
,也替换了text
按钮的类型。 I replaced the this
of serialize()
for id of my form. 我更换了
this
的serialize()
对我的表格ID。
jQuery(document).ready(function($){ $('#enviar').click(function(e){ //I replaced the SUBMIT
for CLICK
var minhaprancha = $('#minhaprancha').serialize(); // I replaced the THIS
for id of my form jQuery(document).ready(function($){$('#enviar')。click(function(e){//我用
CLICK
代替了SUBMIT
var minhaprancha = $('#minhaprancha')。serialize(); //我将THIS
替换为表单的ID
e.preventDefault(); // preventing form submit normal behavior $.ajax({ type: 'POST', url: meuajax.ajaxurl, data: meuajax.minhaprancha, success: function( data ){ $('#resultado').html( 'Sucesso : ' + data ); console.log(data); }, error: function( error ){ $('#resultado').html( 'Erro! : ' + error ); console.log(error); } }); });
}); });
With these modifications, the code worked, but not perfectly. 经过这些修改,代码可以正常运行,但效果并不理想。 I put a
alert
to check if the serialize()
was working and it is!. 我发出了
alert
以检查serialize()
是否正在工作,是否正常! But, in the end of script, the browser console returns me status success, value zero and isn't being made the operation of the function prancha()
. 但是,在脚本末尾,浏览器控制台会向我返回状态成功,值为零,并且不会执行
prancha()
函数的操作。 The data is not registered in the database. 数据未在数据库中注册。
I looked for other ways to try to make the work code:
我在寻找其他方式来制作工作代码:
Getting the values of the fields, keeping a variable and calling it in ajax. 获取字段的值,保留变量并用ajax调用它。 Both saving the fields of the form as a variable declared in direct
data
field and is displayed the Internal Error 500 将表单的字段另存为在直接
data
字段中声明的变量,并显示内部错误500
jQuery(document).ready(function($){
$('#enviar').click(function(e){
var minhaprancha = '$nome='+$("#nome").val()+
'&email='+$("#email").val()+
'&estilo='+$("#estilo").val()+
'&experiencia='+$("#experiencia").val()+
'&altura='+$("#altura").val()+
'&peso='+$("#peso").val(); //GETTING THE VALUES OF FIELDS
e.preventDefault(); // preventing form submit normal behavior
$.ajax({
type: 'POST',
url: meuajax.ajaxurl,
data: { action: 'prancha', minhaprancha },
success: function( data ){
$('#resultado').html( 'Sucesso : ' + data );
console.log(data);
},
error: function( error ){
$('#resultado').html( 'Erro! : ' + error );
console.log(error);
}
});
});
});
I also tried to call the values of the form fields in
data : {}
matrix and is displayed the errorMaximum call stack size exceeded
.我还尝试调用
data : {}
矩阵中表单字段的值,并显示错误Maximum call stack size exceeded
。
jQuery(document).ready(function($){
$('#enviar').click(function(e){
e.preventDefault(); // preventing form submit normal behavior
$.ajax({
type: 'POST',
url: meuajax.ajaxurl,
action: 'prancha',
data: { 'nome':nome, 'email':email, 'estilo':estilo, 'experiencia':experiencia, 'altura':altura, 'peso':peso },
success: function( data ){
$('#resultado').html( 'Sucesso : ' + data );
console.log(data);
},
error: function( error ){
$('#resultado').html( 'Erro! : ' + error );
console.log(error);
}
});
});
});
In my
functions.php
, I left only the part that insert the data in the database.在我的
functions.php
,仅保留了将数据插入数据库的部分。 To see the operation in parts.要部分查看操作。 And remember that, when I put this code directly into my
footer.php
it works perfectly:并记住,当我将这段代码直接放入
footer.php
它可以完美地工作:
function meu_ajax_scripts(){
wp_enqueue_script( 'meuajax', get_template_directory_uri().'/consulta.js', array('jquery'), '1.0', true );
wp_localize_script( 'meuajax', 'meuajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'meu_ajax_scripts');
function prancha(){
if(!empty($_POST)){
$nome = $_POST['nome'];
$email = $_POST['email'];
$estilo = $_POST['estilo'];
$experiencia = $_POST['experiencia'];
$altura = $_POST['altura'];
$peso = $_POST['peso'];
cadastra_usuario($nome, $email, $estilo, $experiencia, $altura, $peso);
}
function cadastra_usuario($nome, $email, $estilo, $experiencia, $altura, $peso){
global $wpdb;
$table = 'dados_usuario';
$data = array(
'nome' => $nome,
'email' => $email,
'estilo' => $estilo,
'experiencia' => $experiencia,
'altura' => $altura,
'peso' => $peso,
);
$updated = $wpdb->insert( $table, $data );
if ( ! $updated ) {
$wpdb->print_error();
}
}
die();
}
add_action('wp_ajax_prancha', 'prancha');
add_action('wp_ajax_nopriv_prancha', 'prancha');
I'm still researching on various blogs, websites and forums trying to work it. 我还在各种博客,网站和论坛上进行研究,以尝试使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.