Reputation: 371
I'm doing something like this, but getting null values even though the JSON looks like it's coming though formatted correctly. To avoid the returned integer values being wrapped in double quotes I added absint
. Any idea where I am going wrong? PHP v.5.5.23. Thanks.
class.php
public function stats($interval) {
global $wpdb;
$title = $this->title;
if (is_object($wpdb) && is_a($wpdb, 'wpdb')) {
$totals = $wpdb->get_results("
SELECT * FROM wp_video_stats WHERE vid_title = '$title' AND DATE(updated) = DATE_SUB(DATE(NOW()), INTERVAL '$interval' DAY)");
}
foreach ($totals as $row) {
$days = absint($row->days);
$weeks = absint($row->weeks);
$months = absint($row->months);
}
return array(
'title'=>$title,
'days'=>$days,
'weeks'=>$weeks,
'months'=>$months
);
}
$array = $results->stats(2);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
header('Content-type: application/json');
echo json_encode($array);
exit();
}
page.php
<script>
$.ajax({
url : '/class.php',
type : 'POST',
dataType : 'json',
success : function (data) {
console.log(data);
},
error : function () {
console.log("error");
}
})
</script>
JSON
{
"title":"title_test",
"days":217,
"weeks":37,
"months":3
}
console.log
Object {title: "title_test", days: null, weeks: null, months: null}
Upvotes: 1
Views: 337
Reputation: 371
I eventually figured this out. A reference to wp-load.php
was required in my custom page. Thankfully I found this post Cant access wp-load.php dynamically showing a way to include the file which worked for me locally.
$root = dirname(dirname(dirname(dirname(__FILE__))));
if (file_exists($root.'/wp-load.php')) {
require_once($root.'/wp-load.php');
} else {
require_once($root.'/wp-config.php');
}
Upvotes: 1