Solo
Solo

Reputation: 6957

Getting a weird 500 error with ajax

Im trying to call PHP with ajax but it throws me 500, any ideas?

I get error code 500 for the file ajax is trying to load!

This code is retrieving data from Google Statistics - Im showing statistics on my site which is fetched if button is pressed via ajax.

PHP Im calling with ajax:

add_action('wp_ajax_rs_ajax_statistics', 'rs_ajax_statistics');
function rs_ajax_statistics() {

try {
  $optParams = array();

    // Required parameter
    $metrics    = 'ga:uniquePageviews';
    $start_date = date('Y-m-d',  strtotime('-10 years'));
    $end_date = date('Y-m-d');

    //Current page path
    $path_name = $_SERVER['REQUEST_URI'];

    $optParams['filters'] = 'ga:pagePath==' . $path_name;

    $result = $analytics->data_ga->get( $analytics_id,
            $start_date,
            $end_date, $metrics, $optParams);

    // Everything is OK
    if( $result->getRows() ) {
        $views_overall = $result->getRows()[0][0];
        echo $views_overall;
    }
} 
// Something is wrong
catch(Exception $e) {
    //echo 'There was an error : - ' . $e->getMessage();
} 
}

Ajax call:

    //Statistics
    var statistics = $('a.statistics');
    var statisticsMessage = $('div.meta-extra');


        statistics.click(function() {

                console.log('Great!');

                jQuery.ajax({
                    url: ajaxURL,
                    type: "get",
                    dataType: "json",
                    data: {
                        'action': 'rs_ajax_statistics'
                    },
                    success: function(msg) {
                        statisticsMessage.html(msg);
                    },
                    error: function() {

                    }
                }); 
        });

Upvotes: 1

Views: 164

Answers (1)

Ben
Ben

Reputation: 683

Log the error you get back in your ajax call

error:function (errorcode, errormsg) {
    console.log (errorcode + ' ' + errormsg);
}

Edit The final answer is: You should always switch error reporting on and solve the errors displayed.

ini_set('display_errors', 1); 
error_reporting(E_ALL);

When using require you should use an absolute path. If it's in your application root you can use $_SERVER['DOCUMENT_ROOT'] to get your absolute path. Otherwise you can use realpath($relative_path) see http://php.net/realpath.

Upvotes: 2

Related Questions