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! 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({
          //CAAL  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);
          }               
      });
    });
    });

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

  • 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. It’s the error of AJAX itself. The field error: function(){ alert('ERRO!!!');},

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.

$299 Affordable Web Design WordPress

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Ajax not working to insert, query and result data

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.