1

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}
3
  • 1
    not posting any data in the ajax Commented Feb 23, 2016 at 19:30
  • The $interval is an argument being passed into the query. Commented Feb 23, 2016 at 19:33
  • How many results are you expecting also? If more than one will overwrite variables in loop. Do a dump of $totals and see it in your console ... echo json_encode($totals); exit; Commented Feb 23, 2016 at 19:41

1 Answer 1

1

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');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Mark your answer also for others help.
Will do Anant I have to wait until tomorrow. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.