通过wordpress中的AJAX从SQL查询中获取结果

时间:2017-05-04 19:33:02

标签: javascript php jquery ajax wordpress

我试图通过Ajax从函数.php中的sql查询函数中获取结果数组。有人可以帮帮我吗? 我发布了代码:

在functions.php文件中

function my_action(){
    global $wpdb;

    $tablename = $wpdb->prefix . 'rg_lead_detail';
    $lead_id = $_POST['fieldvalue'];  // This variable will get the POST 'fieldvalue'
    $form_id = 21;

    $sql = "SELECT * FROM $tablename WHERE lead_id = %d AND form_id= %d";

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

    return $results;
} 

在我的javascript文件中:

(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");
        jQuery.ajax({ // We use jQuery instead $ sign, because Wordpress convention.
        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,
        },
        success: function( response ) { 
            alert(response);           
        }
        });
       }
   });
 });
})(jQuery);

0 个答案:

没有答案