user3879583
user3879583

Reputation:

Can't get it working: jQuery AJAX array to PHP

I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.

The issue

I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.

The scripts

This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.

The jQuery/Ajax part

$(document).ready(function(){
    $.ajaxSetup({cache: false});

    var interval = 30000;
    // var ids = ['1','2','3'];

    var ids = []; // This creates an array like this: ['1','2','3']
    $(".player").each(function() {
        ids.push(this.id);
    });

    setInterval(function() {
        $.ajax({
            type: "POST",
            url: "includes/fetchstatus.php",
            data: {"players" : ids},
            dataType: "json",
            success: function(data) {
                console.log(data);
            }
        });
    }, interval);

});

The PHP part (fetchstatus.php)

if (isset($_POST["players"])) {
    $data = json_decode($_POST["players"], true);

    header('Content-Type: application/json');
    echo json_encode($data);
}

What I'd like

After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3. But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.

All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.


Could someone tell me what exactly I am doing wrong/missing? Perhaps the answer is easier than I think but I can't seem to find out myself.

Best regards, Peter

Upvotes: 1

Views: 1132

Answers (2)

algorhythm
algorhythm

Reputation: 8728

The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json. You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).

And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:

$returningData = array(); // or 'false'

$data = @$_POST['players']; // @ supresses PHP notices if key 'players' is not defined

if (!empty($data) && is_array($data))
{
    var_dump($data); // dump the whole 'players' array

    foreach($data as $key => $value)
    {
        var_dump($value); // dump only one player id per iteration
        // do something with your database
    }

    $returningData = $data;
}

header('Content-Type: application/json');
echo json_encode($returningData);

Using JSON: You can simply use your returning JSON data in jQuery, e.g. like this:

// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
    console.log( index + ": " + value );
});

And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:

$data = array(
    1 => array(
        // data from DB for player with ID 1
    ),
    2 => array(
        // data from DB for player with ID 2
    ),
    ...
);

// [...]
echo json_decode($data);

Upvotes: 1

Bilal
Bilal

Reputation: 2673

What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.

In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.

print_r prints human-readable information about a variable

So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.

Upvotes: 1

Related Questions