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).
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);
}
});
});
});
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:
- In the field `URL` call the native Wordpress `admin-ajax.php`.
- In the field `DATA` call the function that makes the registration, query and displays to the user.
- In the `SUCCESS` field, prints the value of `data`.
FUNCTIONS: I make the registration code in database, do the query and print with the echo
.
The AJAX
is returning me the error message.
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. 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.
First of all, you should use $wpdb object to access the database in Wordpress, including the select. Check the documentation 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:
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: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()
byget_stylesheet_directory_uri()
.As you can see
'meuscript'
is in both functionswp_enqueue_script()
andwp_localize_script()
.Then you will retrieve
'meuajax'
and'ajaxurl'
in yourjQuery
script.They are combined this way:
url: meuajax.ajaxurl,
instead ofurl: 'wp-admin/admin-ajax.php',
.The
wp_localize_script()
function will make the bridge throughadmin_url( 'admin-ajax.php' )
function from yourjQuery script
to yourphp
function…(NEW UPDATE - NOVA ATUALIZAÇÃ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). All the form data is serialized before being sent to your
prancha()
php function through ajax:Put this code in a js file ajax_script.js inside a js subfolder of your active theme (or child theme).
Your html form (an example like), has to be some kind of similar as this one:
Then you will retrieve (as you already know) the data values in your php with:
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
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?
How can I get form data with JavaScript/jQuery?
WPSE - Custom Form with Ajax
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
forclick
in my jQuery and I also replaced the type of my button fortext
.I replaced the
this
ofserialize()
for id of my form.jQuery(document).ready(function($){ $('#enviar').click(function(e){ //I replaced the
SUBMIT
forCLICK
var minhaprancha = $('#minhaprancha').serialize(); // I replaced theTHIS
for id of my form});
With these modifications, the code worked, but not perfectly. I put a
alert
to check if theserialize()
was working and it is!. But, in the end of script, the browser console returns me status success, value zero and isn't being made the operation of the functionprancha()
. The data is not registered in the database.Getting the values of the fields, keeping a variable and calling it in ajax. Both saving the fields of the form as a variable declared in direct
data
field and is displayed the Internal Error 500I'm still researching on various blogs, websites and forums trying to work it.