Using the code that I have below, I am getting the $cid to loop but the $html_string is not looping. It seems to only run once. Why?
php
$query = $wpdb->get_results("SELECT firstname, lastname, id FROM table_name");
add_action("wp_ajax_myphp", "myphp");
add_action("wp_ajax_myphp", "myphp");
function myphp() {
global $query;
$html_string = '';
foreach($a as $value){
$html_string = ['<div class=\"myclass\">'.$value-> firstname.'</div><div class=\"myclass\">'.$value-> lastname.'</div>'];
$cid[] = $value->id;
};
echo json_encode(array('html' => $html_string, 'cid' => $cid));
die;
}
Jquery
jQuery.ajax({
data: {action: 'myphp'},
type: 'post',
url: my_ajax.ajax_url,
dataType: 'JSON',
success: function(data) {
console.log(data);
}
});
sample output from the above code:
cid: Array(3) [ "44", "45", "46" ]
html: (1) […]
0: "<div class=\\\"myclass\\\">Bob</div><div class=\\\"myclass\\\">Smith</div>"
length: 1
It iterates over the cid
three times just as it should but only once
$html_string isn't an array, so it contains the value of the last iteration.
Try
$html_string[] = '<div class=\"myclass\">'.$value-> firstname.'</div><div class=\"myclass\">'.$value-> lastname.'</div>';
and remove
$html_string = '';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.