简体   繁体   中英

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.

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);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM