frrlod
frrlod

Reputation: 6685

Writing interactive PHP with buttons

I'm looking to create a page, which has a set of buttons. These buttons are each tied to different php functions (the things done by these functions have to be done server side). Basically, all the coding is done in php. The php has all the objects, the constants, all the information needed in the page. But all the actions need to be initiated by the user, by clicking the buttons.

But here comes the problem: how can I efficiently mix those php functions with my buttons? Right now I'm using ajax, javascript and jquery but the way I do it feels controversial, here's what I mean:

var continueFight;
$("#playerAttack").click(function() {
    if (continueFight) {    
      AJAX actions here
    }

one of the ajax actions is a $.post, directed to the following page:

<?php
//some fight calculations
if ($fightOver)
  echo "<script>continueFight=false</script>";
?>

In the above, some php calculations are done to decide whether the fight is over, and if it is, it echoes some Javascript and returns it (through the AJAX request) to the main page, which will cause the button to stop running in the future.

This feels very messy. Is there a better way to mix PHP with buttons?

Upvotes: 0

Views: 955

Answers (3)

Kai Qing
Kai Qing

Reputation: 18843

Your approach is exactly as you assumed. You have to treat your PHP as isolated events and not something that's keeping a constant record. Suppose you're making a game. You store the state of the game and any relevant data in a database common to the players, typically using a token passed back and forth.

Your entire game's interactions should be handled client side. By that I mean listeners that send requests to php via ajax. PHP should ONLY return state responses to interpret with js, it should NOT return html or anything goofy like that.

You can add provisions to your php to validate state server side to prevent js manipulation, but that's probably not a huge concern of yours at this point.

Looks like everyone else basically said the same thing but with code samples so I'll cut this here. If you have specific questions, feel free to ask and I may update.

EDIT

State responses would be something like an object, integer to represent a boolean, integer range, score, or anything else used as a simple response to trigger a more complex action in javascript. So suppose you have an attack. Suppose you send the request to PHP to have it decide whether or not the attack was successful and if so, what kind of damage did it do. You might expect to get a response like this from PHP:

$response = array(
    'success' => 1,
    'damage' => 200,
    'enemy_id' => 4
);

echo json_encode($response);

from javascript, assuming your jQuery ajax success was assigning the response to data you could evaluate the response like this:

//assume generically that this object represents the damagable players
var players = {
    0: {
        health: 200
    },
    1: {
        health: 300
    },
    2: {
        health: 30
    },
    3: {
        health: 750
    },
    4: {
        health: 10
    }
};

// and assume this is in your success function in your ajax call
if(data.success == 1)
{
    //successful attack. cause damage
    players[data.enemy_id].health -= data.damage;
    if(players[data.enemy_id].health <= 0)
    {
        // do something to kill enemy
    }
}

Point is, you should return absolutely minimal data to the browser and let the client side handle all the game actions. PHP is just used to sync the game or fetch resources that aren't available to the client.

Upvotes: 2

user428517
user428517

Reputation: 4193

Don't echo chunks of JavaScript back to the page. Write the JavaScript in JavaScript, and pass a flag back from PHP to tell the S what to do:

JavaScript:

var continueFight;
$("#playerAttack").click(function() {
    if (continueFight) {    
        $.post('scriptname.php', function(data) {
            continueFight = data.continueFight;
        });
    }
});

PHP:

<?php

//some fight calculations

echo json_encode(array('continueFight' => !$fightOver));

That's as easy as it gets. Ajax requires a lot of typing, unfortunately.

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71939

I don't see why echoing a script element. Just echo a value (e.g., 1 or nothing), and from the success callback act according to the response:

<?php
//some fight calculations
echo $fightOver;
?>
var continueFight;
$("#playerAttack").click(function() {
    if (continueFight) {    
       $.post(url, {}, function(response) {
           continueFight = !!response; // cast response to boolean
       }
    }
})

Upvotes: 3

Related Questions