Chris Chris - 5 months ago 22
JSON Question

Unexpected end of JSON input

I'm having a little trouble figuring out how to fix this error I'm getting. My code is as follows.

It all starts with a AJAX request whenever the user moves their mouse on the webpage.

$('body').mouseover(function() {
$.ajax({
url: '/core/home.php',
data: {action: 'refresh'},
type: 'post',


Next, the PHP file (home.php) executes a couple methods to get all the needed data and sends it back to AJAX Request.

require_once 'init.php';

if(isset($_POST['action']) && !empty($_POST['action'])) {

// Home Class
$h = new Home();

// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();

// Method to count all "users"
$h->getUsers('id');
$users = $h->count();

// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;

// Use JSON to send the array back
json_encode($arr);

return $arr;
}


Once the AJAX Request receives a success, the following executes

success: function(output) {
obj = JSON.parse(output);

// Separate the parts of the JSON string
vacs = obj[0];
users = obj[1];

// Show the result at the correct position on the webpage
$('#vac_num').html(vacs);
if(vacs == 1) $('#vac_txt').html('is'); else $('#vac_txt').html('zijn');

$('#users_num').html(users);
if(users == 1) $('#users_txt').html('is'); else $('#users_txt').html('zijn');
}
});
});


Unfortunately this code results into an error:
Unexpected end of JSON input
.
Any help is much appreciated.

Answer

Rather than returning variable you need to echo it

require_once 'init.php';

if(isset($_POST['action']) && !empty($_POST['action'])) {

    // Home Class
    $h = new Home();

    // Method to count all "vacs"
    $h->getVacs('id');
    $vacs = $h->count();

    // Method to count all "users"
    $h->getUsers('id');
    $users = $h->count();

    // Create array to store all data
    $arr = array();
    $arr[] = $vacs;
    $arr[] = $users;

    // Use JSON to send the array back
    echo json_encode($arr);
}