jQuery AJAX fetch PHP variables (json?)

I have a PHP file which is called upon through AJAX.

The PHP file “fetch.php” searches the database with the given JS variables, an x and y co-ordinate, through GET, and brings back the user id associated with those co-ordinates.

So I then get that users information…

I’m then trying to bring those PHP variables back into the AJAX call on the original page and display the results… here’s what I’ve got so far…

Javascript/jQuery


<script type="text/javascript">

    jQuery.fn.elementlocation = function() {

        var curleft = 0;
        var curtop = 0;

        var obj = this;

        do {

        curleft += obj.attr('offsetLeft');
        curtop += obj.attr('offsetTop');

        obj = obj.offsetParent();

        } while ( obj.attr('tagName') != 'BODY' );


            return ( {x:curleft, y:curtop} );

    };


    $(document).ready( function() {

        $("#gdimage").mousemove( function( eventObj ) {

            var location = $("#gdimage").elementlocation();
            var x = eventObj.pageX - location.x;
            var x_org = eventObj.pageX - location.x;
            var y = eventObj.pageY - location.y;
            var y_org = eventObj.pageY - location.y;

            x = x / 5;
            y = y / 5;

            x = (Math.floor( x ) + 1);
            y = (Math.floor( y ) + 1);

            if (y > 1) {

                block = (y * 200) - 200;
                block = block + x;

            } else {

                block = x;

            }

            $("#block").text( block );
            $("#x_coords").text( x );
            $("#y_coords").text( y );

            if (x == x_org + 5 || x == x_org - 5 || y == y_org + 5 || x == y_org - 5) {

                $.ajax({
                    type: "GET",
                    url: "fetch.php",
                    data: "x=" + x + "&y=" + y + "",
                    dataType: "json",
                    async: false,
                    success: function(data) {
                        $("#user_name_area").html(data.username);
                        $("#user_online_area").html(data.online);
                    }
                });

            }

        });

    });

</script>

The displayed PHP file with the Javascript/jQuery:


<div class="tip_trigger" style="cursor: pointer;">

    <img src="gd_image.php" width="1000" height="1000" id="gdimage" />

    <div id="hover" class="tip" style="text-align: left;">
        Block No. <span id="block"></span><br />
        X Co-ords: <span id="x_coords"></span><br />
        Y Co-ords: <span id="y_coords"></span><br />
        User: <span id="user_name_area"></span>
        Online: <span id="user_online_area"></span>
    </div>

</div>

PHP file (fetch.php) called through AJAX


<?

    require('connect.php');

    $mouse_x = $_GET['x'];
    $mouse_y = $_GET['y'];

    $grid_search = mysql_query("SELECT * FROM project WHERE project_x_cood = '$mouse_x' AND project_y_cood = '$mouse_y'") or die(mysql_error());

    $user_exists = mysql_num_rows($grid_search);

    if ($user_exists == 1) {

        $row_grid_search = mysql_fetch_array($grid_search);

        $user_id = $row_grid_search['project_user_id'];


        $get_user = mysql_query("SELECT * FROM users WHERE user_id = '$user_id'") or die(mysql_error());

        $row_get_user = mysql_fetch_array($get_user);

        $user_name = $row_get_user['user_name'];
        $user_online = $row_get_user['user_online'];

        echo "{ username: $user_name }";
        echo "{ online: $user_online }";

    } else {

        echo "{ username: }";
        echo "{ online: }";

    }

?>

Everything is working fine, except one thing, I’ve check the php file and it does echo a username so I know there is a result being sent back from my query. It’s just I can’t seem to get the user_name_area and user_online_area to display the results from the fetch.php file.

Am I parsing them correctly, do I have to assign them to a variable or is what I’m trying to do impossible?

I’ve never attempted this whole json thing before and I seem to be having some problems with it, so if anyone could give me a hand cause I’ve been trying for the past couple nights to get it to work and just… can’t!!

Use Chrome first, then use its console (CTRL + SHIFT + I) to check what you’re getting is actually valid JSON.

Then, to make your life easier - you can use PHP’s native function called json_encode() that will properly make stuff in JSON format without having you worry whether you constructed something right or not.

So, the php part of your script can look like this:

$user_name = $row_get_user['user_name'];
$user_online = $row_get_user['user_online'];

$json['username'] = $user_name;
$json['user_online'] = $user_online;

echo json_encode($json);

That should at least put you on the right track and give you an insight whether you have errors in your JS code or not.

I’ve tried the json_encode function already tonight but slightly different to how you’ve written it.

I used:


$user_name = $row_get_user['user_name'];

echo json_encode($user_name);

That didn’t actually work, and changing it to your approach didn’t work either…

HOWEVER, I have just got rid of the if statement around the AJAX call, and it appears to be working just fine now! I’m also using your method for json_encode too since I can put query results into an array if I’m not mistaken?

For json_encode to work you need to make sure an array is been sent to it and not a string.

Eg.

echo json_encode($user_name);

Wont work because its a string not an array

echo json_encode($row_get_user);

Will work because $row_get_user is already an array and can be converted to a JSON object array.

Within your JS script you can then use

$.ajax({
    success: function(data) {
        alert(data['user_name']);
    }
});

Ah, I see!

So if I was to, for example, bring back the list of say 5 of the usernames and place them in an array. How would you separate them to display them within the success function of the AJAX which could be placed in the span tags?


$("#user_name_1_area").html(data.username1);
$("#user_name_2_area").html(data.username2);
etc...

Or would you need to do something like:


$("#user_name_1_area").html(data.username[0]);
$("#user_name_2_area").html(data.username[1]);
etc...

Thanks for explaining the string/array though, I wasn’t aware of that!

It depends how you build your array

Example 1

echo json_encode(array('username1' => $username1, 'username2' => $username2));

Example 2

echo json_encode(array('username' => array($username1, $username2)));