Can someone help me out? It seems like I get a string instead of an array. Once I pass the array, which is the result of a sql query, from PHP to Javascript through AJAX, I would like to loop the array and populate some fields in a form. I post the code:
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(data) {
alert( data );
//Here I would like to loop the array and get the values
}
});
}
});
});
})(jQuery);
PHP (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;
$tablename = $wpdb->prefix . 'rg_lead_detail';
$lead_id = $_POST['fieldvalue']; // This variable will get the POST 'fieldvalue'
$form_id = 21;
$sql = "SELECT value FROM $tablename WHERE lead_id = %d AND form_id= %d";
$results = $wpdb->get_results( $wpdb->prepare( $sql, $lead_id, $form_id ), ARRAY_A );
echo json_encode($results,JSON_FORCE_OBJECT);
}