Get results from SQL query through AJAX in wordpress

I am trying to get the results array from a function with sql query in the file functions.php through Ajax. Could someone help me out?
I post the code:

In the file functions.php

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // This lines it's because we are using AJAX on the FrontEnd.

function my_action(){
    global $wpdb;

    $lead_id = $_POST['fieldvalue'];  // This variable will get the POST 'fieldvalue'
    $form_id = 21;
    $sql = "SELECT * FROM $tablename WHERE lead_id = $lead_id AND form_id= $form_id";

    $results = $wpdb->get_results( $wpdb->prepare( $sql, $form_id, $field_id ), ARRAY_A );

    echo json_encode($results);
    die();
} 

in my javascript file:

function($){
$(document).ready(function() {
   $('#input_12_153').change(function (){
       if ($('#input_12_153').attr("value")== 'no-selection'){
            $('#input_12_48').val( '' );}
       else{
            var valor = $('#input_12_153').attr("value");
        $.ajax({ 
        url : '/optcat/wp-admin/admin-ajax.php', // This addres will redirect the query to the functions.php file, where we coded the function that we need.
        type : 'POST',
        data : {
            action : 'my_action', 
            fieldvalue : valor,
        },
        dataType: 'json',
        success: function( response ) {
            var obj = jQuery.parseJSON(response); 
            $('#input_12_48').val(obj[1]);            
        }
        });
       }
   });
 });
})(jQuery);

Read more here: Get results from SQL query through AJAX in wordpress

Leave a Reply

Your email address will not be published. Required fields are marked *