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

in my javascript file:

$(document).ready(function() {
   $('#input_12_153').change(function (){
       if ($('#input_12_153').attr("value")== 'no-selection'){
            $('#input_12_48').val( '' );}
            var valor = $('#input_12_153').attr("value");
        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); 

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


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: