Jump to content

Can A Button Click Run A PHP Function?


twilitegxa

Recommended Posts

Is there a way to run a php function when a button is pressed? Or is that something that you do with JavaScript? I have a page that might be a little confusing. It uses JavaScript to run some PHP script to display different tables of information on my page. Here are the pages:

 

first page:

<?php
$get_scouts = "select * from scouts where username = '".$_SESSION['userName']."'";
$get_scouts_res = mysql_query($get_scouts, $conn) or die(mysql_error());
echo "<select name=\"users\" onchange=\"showUser(this.value)\">
<option selected=\"selected\">None Selected</option>";
    while ($list_scouts = mysql_fetch_array($get_scouts_res)) {
    $identity = ucwords($list_scouts['identity']);
    $topic_id = $list_scouts['id'];
echo "<OPTION value=\"$identity\">$identity</OPTION>";
}
echo "</select>";
?>
   Select an area:

<?php
$get_map = "select * from monsters1 group by map";
$get_map_res = mysql_query($get_map, $conn) or die(mysql_error());
echo "<select name=\"maps\" onchange=\"showMap(this.value)\">
<option selected=\"selected\">None Selected</option>";
while ($list_maps = mysql_fetch_array($get_map_res)) {
$map_id = $list_maps['id'];
$map = $list_maps['map'];
echo "<option value=\"$map\">$map</option>";
}
echo "</select>";
?>
<div id="txtHint2"></div>
<table>
<tr>
<td valign="top">
<div id="txtHint"></div>
</td>
<td valign="top"><div id="txtHint3"></div></td>
</tr>
</table>
</form>

 

Here is the JavaScript:

 

//code to display maps
var xmlhttp;

function showUser(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
var url="getuser.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

//code to display locations

var xmlhttp2;

function showMap(str)
{
xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
var url2="getlocations.php";
url2=url2+"?q="+str;
url2=url2+"&sid="+Math.random();
xmlhttp2.onreadystatechange=stateChanged2;
xmlhttp2.open("GET",url2,true);
xmlhttp2.send(null);
}

function stateChanged2()
{
if (xmlhttp2.readyState==4)
{
document.getElementById("txtHint2").innerHTML=xmlhttp2.responseText;
}
}

function GetXmlHttpObject2()
{
if (window.XMLHttpRequest2)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest2();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

//code to display monsters

var xmlhttp3;

function showMonsters(str)
{
xmlhttp3=GetXmlHttpObject();
if (xmlhttp3==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
var url3="getmonsters.php";
url3=url3+"?q="+str;
url3=url3+"&sid=";
xmlhttp3.onreadystatechange=stateChanged3;
xmlhttp3.open("GET",url3,true);
xmlhttp3.send(null);
}

function stateChanged3()
{
if (xmlhttp3.readyState==4)
{
document.getElementById("txtHint3").innerHTML=xmlhttp3.responseText;
}
}

function GetXmlHttpObject3()
{
if (window.XMLHttpRequest3)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest3();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

 

Here is the getuser.php:

 

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("smrpg", $con);

$sql="SELECT * FROM derived_values WHERE identity = '".$q."'";

$result = mysql_query($sql);

echo "<table border='0'>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td colspan=2><strong>" . $row['identity'] . "</strong></td></tr>";
  echo "<tr><td align=right><i>Health</i></td><td>" . $row['health'] . "/" . $row['full_health'] . "</td></tr>";
  echo "<tr><td align=right><i>Energy</i></td><td>" . $row['energy'] . "/" . $row['full_energy'] . "</td></tr>";
  echo "<tr><td align=right><i>Attack</i></td><td>" . $row['acv1'] . "</td></tr>";
  echo "<tr><td align=right><i>Defense</i></td><td>" . $row['dcv1'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?> 

 

Here is the getlocations.php:

 

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("smrpg", $con);

$sql="SELECT * FROM monsters1 WHERE map = '".$q."' group by location";

$result = mysql_query($sql);

echo "<table border='0'>";
echo "Select a location: <select name=\"locations\" onchange=\"showMonsters(this.value)\">
<option selected=selected>None Selected</option>";

while($row = mysql_fetch_array($result))
  {
  $location = $row['location'];
   echo "<option value=\"$location\">" . $row['location'] . "</option>";
  }
echo "</select>";

mysql_close($con);
?> 

 

Here is the getmonsters.php:

 

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("smrpg", $con);

$sql="SELECT * FROM monsters1 WHERE location = '".$q."' group by name order by rand() limit 1";

$result = mysql_query($sql);

echo "<table border='0'>";
echo "<tr><td>";

while($row = mysql_fetch_array($result))
  {
   echo "<strong>" . $row['name'] . "</strong></td>";
  }
echo "</tr></table><br />";

//function for Attack
function attackMonster()
{
echo "test attack";
}

echo "<form><input id=\"attack\" type=\"button\" value=\"Attack\" onlick=\"attackMonster()\">  <input type=\"button\" value=\"Magic\">  <input type=\"button\" value=\"Item\"></form>";

mysql_close($con);
?> 

 

On this last part, the getmonsters.php page, I have three buttons: Attack, Item, and Magic. I would like to know if I can set the Attack button, for example, to run a php script that updates the $health and $energy fields based on some formula? I would need to take the $acv1 variable and create a formula that would figure out the attack damage amount and then the php function would need to update the $health field in the table. Is this possible to do with PHP? Can you set a button to run a php function upon being clicked? Or would I have to use a JavaScript function that ran the PHP functon, or how can I do this? Can anyone help me out with this?

 

 

Link to comment
Share on other sites

I found this example:

 

<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php 
$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("smrpg", $con);
$sql = ('UPDATE derived_values SET health = 7, energy = 5 WHERE identity = "Sailor Reese"'); 
$result = mysql_query($sql); 
echo "it worked"  ?>";
}
</script>

<input type="button" value="Attack" onClick="test(); return false;">

<span id="php_code"> </span>

 

I altered it to see if it would work, and it does, but I need some help getting my values because right now I'm just using constants. I need to get the $identity to equal the identity field first.

Link to comment
Share on other sites

twilitegxa I like all the code you doing.  Fun stuff.

 

I just got 1 question for you, how is your website or whatever set up?

Cause from what im reading on this topic it shoulds like a web 2.0 type page, which is AJAX, FLASH, whatever else is REAL-TIME ran.  but ya thats my question is this a website that loads all data VIA - AJAX or the old fashion way of links from page to page?

 

Really i would love to help you but i got to know where your coming from.  Most people dont do 2.0 Web-designed websites.

 

However i'll give you a short answer to your questions.  I would get all the PHP data you need and store them in javascript varibles.  If the varibles need updating  or changing have that done through AJAX manually, or automatically every few seconds or minutes, or when another function is activated.

Link to comment
Share on other sites

  • 2 weeks later...

Well, to answer your question, I'm using mostly PHP and MySQL to load all information onto my web pages. I'd love to use something like AJAX maybe in this particular instance probably, unless there's a better way, I just don't know how to code in AJAX very much yet. But your suggestion about storing all my PHP data into JavaScript variables, how could I go about doing that? I'm still new to JavaScript and am trying to learn more.

 

I'm not sure if the page needs to be real-time ran or not. What I want to do is have a sort of text-based browser game, kind of liek the ones you see on MySpace and Facebook. Similar, but also kind of different. The similarity is basically the fact that you have a character that can fight monsters and each attack lowers their hit points until their dead. So what I'm trying to do is have a list of characters that the user can pick from once they are logged in, then they choose an area to fight in, then a location within that area, then it would generate a random monster in that area and then they could attack, use an item, use magic skills, or defend. I'd like to be able to use like a PHP function for when the user clicks the attack button that it would run a PHP script that would update the monster's hit points, and then once the battle was over, it would reset the hits points back to full health for that monster so it could be fought again or something.

 

I'm not sure if this has to be done with something like AJAX, but I was wondering if anyone knew if it could be done with something I know a little better like PHP. Or I was hoping someone could at least point me in the right direction if i needed to use something like AJAX or JavaScript and how I might go about using it.

Link to comment
Share on other sites

Hi twilitegxa,

 

I'm not sure I understand 100% if this is what you want, but your option menu clearly invokes the showuser() function in Javascript.  This of course, calls the getuser.php script and passes is the ID of the user that is supposed to be updated.  Can't you just save away that identity immediately inside of getuser.php into your session?  Something like:

 

<?php
$q=$_GET["q"];
$_SESSION["identity"] = $q;

 

I'm not sure that you can just print a form in HTML and have a button directly invoke a PHP script.  But you can certainly do it in Javascript -- you have already done it!  All you really need to do is copy your showuser() function and then modify it slightly -- let's call the new function updatemonster().  Inside of updatemonster(), instead of performing a GET request to getuser.php couldn't you just call updatemonster.php (or whatever you choose to call it) and pass it your acv1 variable?  Then in updatemonster.php you can grab everything you need out of your SESSION or GET arguments and do whatever code you want to randomly update the values in PHP.  The buttons for magic or whatever would just call the updatemonster() function instead of showuser():

 

<input type="button" name="magic" value="Magic" onClick="updatemonster(acv1)">

 

 

Maybe I'm missing something though.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.