Wordpress:Ajax无法插入,查询和结果数据

时间:2022-10-10 16:38:18

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).

在我的网站上,通过我在数据库中发送/注册相同信息的表单,执行SELECT /查询并返回它!返回保存在数据库中的最后一个表,只是刚刚在表单上输入的用户(以及来自数据库的更多信息)。

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:

我想如何在模态引导程序中显示来自数据库的这些值,页面不需要刷新。为此,我按如下方式插入了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:

  • In the field `URL` call the native Wordpress `admin-ajax.php`.
  • 在`URL`字段中调用本机Wordpress`admin -ajax.php`。
  • In the field `DATA` call the function that makes the registration, query and displays to the user.
  • 在“DATA”字段中调用向用户进行注册,查询和显示的功能。
  • In the `SUCCESS` field, prints the value of `data`.
  • 在`SUCCESS`字段中,打印`data`的值。

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 theecho' 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.

注意1:当我插入我的'函数中的代码,注册代码,查询和theecho'以直接方式显示时,在我的footer.php中,它可以工作。因此,我们可以理解错误甚至不在插入,查询或显示的代码中。注2:我想在模态boostrap中显示数据库的返回。起初我只是在屏幕上显示,检查一切正常。在那之后,我将研究如何将这些数据放入模态中,虽然不是帖子的主要主题,但也欢迎提出如何做到这一点的建议。

3 个解决方案

#1


1  

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

首先,您应该使用$ wpdb对象来访问Wordpress中的数据库,包括select。查看文档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' 
} 

#2


1  

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_stylesheet_directory_uri()替换get_template_directory_uri()。

As you can see 'meuscript' is in both functions wp_enqueue_script() and wp_localize_script().

正如您所看到的,'meuscript'在函数wp_enqueue_script()和wp_localize_script()中都有。

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',.
The wp_localize_script() function will make the bridge through admin_url( 'admin-ajax.php' ) function from your jQuery script to your php function…

它们以这种方式组合:url:meuajax.ajaxurl,而不是url:'wp-admin / admin-ajax.php',. wp_localize_script()函数将通过admin_url('admin-ajax.php')函数从你的jQuery脚本到你的php函数...


(NEW UPDATE - NOVA ATUALIZAÇÃO)
regarding your comments, your answer/question update, and this thread too…

(新更新 - NOVASYUALIZAÇÃO)关于您的评论,您的答案/问题更新,以及此主题......


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:

所以这是您最新更新的jQuery代码(使用与表单数据相关的不同方法)。所有表单数据在通过ajax发送到prancha()php函数之前被序列化:

// 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:

参考文献:

#3


0  

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.

你发给我的代码仍然没有用。我做了一些改变,它在部分工作。

  • I replaced the submit for click in my jQuery and I also replaced the type of my button for text.
  • 我替换了我在jQuery中单击的提交,我也替换了我的按钮类型的文本。
  • I replaced the this of serialize() for id of my form.

    我将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){//我替换了SUBMIT for CLICK 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 alertto check if the serialize() 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 function prancha(). The data is not registered in the database.

通过这些修改,代码可以工作,但并不完美。我发出警报,检查序列化()是否正常工作,它是!但是,在脚本结束时,浏览器控制台返回状态成功,值为零,并且没有进行函数prancha()的操作。数据未在数据库中注册。

Wordpress:Ajax无法插入,查询和结果数据

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. Both saving the fields of the form as a variable declared in direct data field and is displayed the Internal Error 500

获取字段的值,保留变量并在ajax中调用它。两者都将表单的字段保存为在直接数据字段中声明的变量,并显示内部错误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);
            }               
        });
    });
  });

Wordpress:Ajax无法插入,查询和结果数据

I also tried to call the values of the form fields in data : {} matrix and is displayed the error Maximum call stack size exceeded.

我还尝试在data:{}矩阵中调用表单字段的值,并显示错误超出最大调用堆栈大小。

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

Wordpress:Ajax无法插入,查询和结果数据

In my functions.php, I left only the part that insert the data in the database. To see the operation in parts. And remember that, when I put this code directly into my footer.php it works perfectly:

在我的functions.php中,我只留下了在数据库中插入数据的部分。要查看部分操作。请记住,当我将此代码直接放入我的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.

我还在研究试图使用它的各种博客,网站和论坛。

#1


1  

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

首先,您应该使用$ wpdb对象来访问Wordpress中的数据库,包括select。查看文档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' 
} 

#2


1  

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_stylesheet_directory_uri()替换get_template_directory_uri()。

As you can see 'meuscript' is in both functions wp_enqueue_script() and wp_localize_script().

正如您所看到的,'meuscript'在函数wp_enqueue_script()和wp_localize_script()中都有。

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',.
The wp_localize_script() function will make the bridge through admin_url( 'admin-ajax.php' ) function from your jQuery script to your php function…

它们以这种方式组合:url:meuajax.ajaxurl,而不是url:'wp-admin / admin-ajax.php',. wp_localize_script()函数将通过admin_url('admin-ajax.php')函数从你的jQuery脚本到你的php函数...


(NEW UPDATE - NOVA ATUALIZAÇÃO)
regarding your comments, your answer/question update, and this thread too…

(新更新 - NOVASYUALIZAÇÃO)关于您的评论,您的答案/问题更新,以及此主题......


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:

所以这是您最新更新的jQuery代码(使用与表单数据相关的不同方法)。所有表单数据在通过ajax发送到prancha()php函数之前被序列化:

// 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:

参考文献:

#3


0  

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.

你发给我的代码仍然没有用。我做了一些改变,它在部分工作。

  • I replaced the submit for click in my jQuery and I also replaced the type of my button for text.
  • 我替换了我在jQuery中单击的提交,我也替换了我的按钮类型的文本。
  • I replaced the this of serialize() for id of my form.

    我将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){//我替换了SUBMIT for CLICK 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 alertto check if the serialize() 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 function prancha(). The data is not registered in the database.

通过这些修改,代码可以工作,但并不完美。我发出警报,检查序列化()是否正常工作,它是!但是,在脚本结束时,浏览器控制台返回状态成功,值为零,并且没有进行函数prancha()的操作。数据未在数据库中注册。

Wordpress:Ajax无法插入,查询和结果数据

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. Both saving the fields of the form as a variable declared in direct data field and is displayed the Internal Error 500

获取字段的值,保留变量并在ajax中调用它。两者都将表单的字段保存为在直接数据字段中声明的变量,并显示内部错误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);
            }               
        });
    });
  });

Wordpress:Ajax无法插入,查询和结果数据

I also tried to call the values of the form fields in data : {} matrix and is displayed the error Maximum call stack size exceeded.

我还尝试在data:{}矩阵中调用表单字段的值,并显示错误超出最大调用堆栈大小。

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

Wordpress:Ajax无法插入,查询和结果数据

In my functions.php, I left only the part that insert the data in the database. To see the operation in parts. And remember that, when I put this code directly into my footer.php it works perfectly:

在我的functions.php中,我只留下了在数据库中插入数据的部分。要查看部分操作。请记住,当我将此代码直接放入我的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.

我还在研究试图使用它的各种博客,网站和论坛。