javascript - Writing interactive PHP with buttons -


i'm looking create page, has set of buttons. these buttons each tied different php functions (the things done these functions have done server side). basically, coding done in php. php has objects, constants, information needed in page. actions need initiated user, clicking buttons.

but here comes problem: how can efficiently mix php functions buttons? right i'm using ajax, javascript , jquery way feels controversial, here's mean:

var continuefight; $("#playerattack").click(function() {     if (continuefight) {           ajax actions here     } 

one of ajax actions $.post, directed following page:

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

in above, php calculations done decide whether fight over, , if is, echoes javascript , returns (through ajax request) main page, cause button stop running in future.

this feels messy. there better way mix php buttons?

your approach assumed. have treat php isolated events , not that's keeping constant record. suppose you're making game. store state of game , relevant data in database common players, typically using token passed , forth.

your entire game's interactions should handled client side. mean listeners send requests php via ajax. php should return state responses interpret js, should not return html or goofy that.

you can add provisions php validate state server side prevent js manipulation, that's not huge concern of yours @ point.

looks else said same thing code samples i'll cut here. if have specific questions, feel free ask , may update.

edit

state responses object, integer represent boolean, integer range, score, or else used simple response trigger more complex action in javascript. suppose have attack. suppose send request php have decide whether or not attack successful , if so, kind of damage did do. might expect response php:

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

from javascript, assuming jquery ajax success assigning response data evaluate response this:

//assume generically object represents damagable players var players = {     0: {         health: 200     },     1: {         health: 300     },     2: {         health: 30     },     3: {         health: 750     },     4: {         health: 10     } };  // , assume in success function in ajax call if(data.success == 1) {     //successful attack. cause damage     players[data.enemy_id].health -= data.damage;     if(players[data.enemy_id].health <= 0)     {         // kill enemy     } } 

point is, should return absolutely minimal data browser , let client side handle game actions. php used sync game or fetch resources aren't available client.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -