So I am making Text based browser game. I have made map where you can move around without refreshing page and updating it with javascript. I have added that it randomly generates bots from database which you can attack, but can't find a way to make it update when you move around the map.
This is the PHP I made to load the bots from database and make then randomly generate.
$sql3 = "SELECT * FROM monsters WHERE botworld='$world'";
$result3 = mysqli_query($conn,$sql3);
$row3=mysqli_fetch_array($result3,MYSQLI_ASSOC);
$rowsbot = array();
while ($rowbot = mysqli_fetch_assoc($result3)) {
$rowsbot[] = $rowbot;
}
for($i=0;$i<count($rowsbot);$i++) {
$a = rand(0,10);
if($a > 5) {
echo "<div class='botres$i'>";
echo "<div class='panel panel-default bot$i'><div class='panel-body bot1$i'>";
echo $i . ". " . $rowsbot[$i]['name'];
echo "<div class='pull-right'><button class='btn btn-default' botid='" . $rowsbot[$i]['id'] ."' botnr='" . $i . "'>Attack</button></div>";
echo "</div></div>";
echo "</div>";
}
}
I added then it automaticly updates the div block when you attack bot. But I want to make bots update when you move around.
I have got the array with data, but don't know how to use it.
var myArray = jQuery.parseJSON('<?php print json_encode($row3); ?>');
console.log(myArray)
Done
var rowsbot = <?php echo json_encode($rowsbot) ?>;
for(i=0; i<rowsbot.length; i++) {
var a = Math.floor((Math.random() * 10) + 1);
if(a>5) {
$(".monsters").append("<div class='botres" + i + "'><div class='panel panel-default bot" + i + "'><div class='panel-body bot1 " + i + "'>" + i + ". " + rowsbot[i].name + "<div class='pull-right'><button class='btn btn-default' botid='" + rowsbot[i].id + "' botnr='" + i + "'>Attack</button></div></div></div></div>");
}
}
Related
i have a table where i display a live price which comes from a cron file that updates every 30seconds or 1 minute, and i have a variable that is filled from that cron job, how do i display it in real-time and make the calculations with php without refreshing the page.
$sql = "SELECT * FROM open_trades WHERE user_id='$session->username' ORDER BY `close_time` DESC ";
$result = $db->prepare($sql);
$result->execute();
while ($row = $result->fetch()) {
if ($row["type"] == "Buy") {
$profit_c = (float) $row["volume"] * (float) $row["live_price"] - $row["cost"];
$fee = 4.9;
$profit = $profit_c * $row["laverage"] - $fee;
}
if ($row["type"] == "Sell") {
$profit_c = (float) $row["volume"] * (float) $row["live_price"] - $row["cost"];
$fee = 4.9;
$profit = $profit_c * $row["laverage"] - $fee;
$profit_sell = $profit * -1;
}
if ($row["type"] == "Buy") {
$profit_trd = $profit;
} else {
$profit_trd = $profit_sell;
}
if ($profit_trd >= 0) {
$col = "profit";
} else {
$col = "loss";
}
if ($profit_trd >= 0) {
$col_b = "#26b276";
} else {
$col_b = "#f73e4a";
}
$open_pl += $profit_trd;
$percentage = ((float) $profit_trd * 100) / (float) $row["cost"];
echo '<tr style="border-right: 2px solid ' . $col_b . ';" class="d-flex justify-content-between" >';
echo "<td>" . $row["time"] . "</td>";
echo "<td>" . $row["asset"] . "</td>";
echo "<td>" . $row["type"] . "</td>";
echo "<td>" . (float) $row["volume"] . "</td>";
echo "<td>1:" . $row["laverage"] . "</td>";
echo "<td>" . (float) round($row["cost"], 2) . '$</td>';
echo "<td>" . (float) $row["buy_price"] . '$</td>';
echo "<td>" . (float) $row["live_price"] . '$</td>';
echo '<td class="' . $col . '" >' . (float) round($profit_trd, 2) . '$</td>';
echo "<td>Close Trade </td>";
echo "</tr>"; }
the $row['live_price'] is the variable i need to get it on realtime everytime it updates from the cron job and also did the $profit_trd updates once it updates, or every PHP calculation requires reload?
Thanks and sorry for my amateur questions!?
You need to use XMLHttpRequest or Websocket to make asynchronus calls from your browser without reloading the page.
Please read MDN Web Docs for more information.
Here are a great comparison of this.
I have a script below to pull some data from sql:
<?php
require 'admin-db.php';
// Define and perform the SQL query
$sql = "SELECT `id`, `first_name`, `last_name`, `status_time` "
. "FROM `staffs` ORDER BY `id` DESC";
$result = $DB_CON->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
$data_row = '<table class="table table-striped tablesorter">'
. '<thead>'
. '<tr>'
. '<th>ID</th>'
. '<th>Fist Name</th>'
. '<th>Last Name</th>'
. '<th>Status Time</th>'
. '</tr>'
. '<tbody>';
foreach($result as $row) {
$data_row .= '<tr>'
. '<td scope="row" class="text-center">'.$row['id'].'</td>'
. '<td>' .$row['first_name'].'</td>'
. '<td>' .$row['last_name'].'</td>'
. '<td><div class="status">' .$row['status_time']. '</div><span class="fa fa-times-circle"></span></td>';
}
}
$data_row .= '</tbody>'
. '</table>';
echo $data_row;
How would I change my script (see below) to compare between the $row['status_time'] and NOW() to indicate if the time different is more than 30 seconds it return 0 and if less than 30 seconds it return a 1 as text in the div class="status"?
<script>
$('.status:contains(">30 seconds") = $this.text(0) else $this.text(1);
</script>
This can be what are you looking for.
// foreach tr row
$.each($('tr .status'), function(i, v) {
// get seconds from date
var seconds = (Date.now() - Date.parse($(v).text()))/1000;
if(seconds) {
(seconds < 30) ? $(this).text('1') : $(this).text('0');
}
});
JSFIDDLE DEMO
My end goal is to click a row on the table and for that to populate in the form next to it for an update. This code here is simply just "attempting" to click a row and for it to display in a Javascript alert with the row data, before I code the population of the form.
Here I have populated the table using PHP. The TR class have "updatetbl" which is later used with the javascript. I used the code example from this question: Get the table row data with a click
if ($patients->num_rows > 0){
while($row = $patients-> fetch_assoc()) {
echo '<tr class="updatetbl">';
echo '<td class="updatetbl">' . $row['ID'] . '</td>';
echo '<td class="updatetbl">' . $row['Forename'] . '</td>';
echo '<td class="updatetbl">' . $row['Surname'] . '</td>';
echo '<td class="updatetbl">' . $row['DOB'] . '</td>';
echo '<td class="updatetbl">' . $row['Address'] . '</td>';
echo '<td class="updatetbl">' . $row['Postcode'] . '</td>';
echo '<td class="updatetbl">' . $row['Telephone'] . '</td>';
echo '<td class="updatetbl">' . $row['Email'] . '</td>';
echo '<tr>';
}
}else{
echo "0 results";
}
I am trying to get the data, firstly, into an alert with Javascript (I just want to see that I have the data before putting into the form)
To populate the alert, and register the click I have the following javascript.
<script>
$("tr.updatetbl").click(function(){
var tableData = $(this).children("td").map(function(){
return $(this).text();
}).get();
alert("Data = "+ $trim(tableData[0]) + " , " + $trim(tableData[1]) + " , "
+ $trim(tableData[2]) + " , " + $trim(tableData[3]) + " , "));
});
</script>
To my knowledge the tr.updatetbl concentrates on a click here? And then gathers the table data..
Any ideas?
Update: I do have etc.
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Forename</th>
<th>Surname</th>
<th>D.O.B</th>
<th>Address</th>
<th>Postcode</th>
<th>Tel</th>
<th>Email</th>
</tr>
</thead>
<?php
$servername = removed
$dbname = removed
$username = removed
$password = removed
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die('Could not connect: ' . $connection->connect_error);
}
$sql = "SELECT ID, Forename, Surname, DOB, Telephone, Email, Address, Postcode FROM people";
$people= $connection->query($sql);
if ($patients->num_rows > 0){
while($row = $patients-> fetch_assoc()) {
echo '<tr class="updatetbl">';
echo '<td>' . $row['ID'] . '</td>';
echo '<td>' . $row['Forename'] . '</td>';
echo '<td>' . $row['Surname'] . '</td>';
echo '<td>' . $row['DOB'] . '</td>';
echo '<td>' . $row['Address'] . '</td>';
echo '<td>' . $row['Postcode'] . '</td>';
echo '<td>' . $row['Telephone'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '</tr>';
}
}
else
{
echo "0 results";
}
$connection->close();
?>
</table>
Solved:
I have it figured out - I put the compiled code into a new jFiddle with the javascript and it still didn't work. I couldn't figure why, so I looked at yours and I noticed at the side you had the library as jQuery! Mine was standard JS. So I realised that I hadn't included the <script src="jquery-1.11.3.min.js"></script>
I voted the below answer because I was helped effortlessly although I am sure after all of this other answers will work.
You have one ")" at the end this line which is not needed, thats why it doesnt work :
`alert("Data = "+ $trim(tableData[0]) + " , " + $trim(tableData[1]) + " , "
+ $trim(tableData[2]) + " , " + $trim(tableData[3]) + " , ")); which isnt needed.
Moreover, just add the class updatetbl on row.
HTML
<table>
<tbody>
<tr class="updatetbl">
<td >ID</td>
<td >Forename</td>
<td >Surname</td>
<td >DOB</td>
<td >Address</td>
<td >Postcode</td>
<td >Telephone</td>
<td >Email</td>
</tr>
<tbody>
</table>
JS :
$(".updatetbl").click(function(){
var tableData = $(this).children("td").map(function(){
return $(this).text();
}).get();
alert("Data = "+ tableData[0] + " , " + tableData[1] + " , "
+ tableData[2] + " , " + tableData[3] + " , ");
});
How about;
$("tr.updatetbl").click(function(){
var data = [];
$("tr.updatetbl td").each(function(i, td){
data.push(td.text());
});
console.log(data);
});
Please find the below code for this
$( "table tr.updatetbl" ).on( 'click', function( e ) {
e.preventDefault();
var data = [];
$( this ).find( "td" ).each( function(){ data.push( $.trim( $( this ).text() ) ) } );
console.log( data );
});
fiddle link : https://jsfiddle.net/4tk4w0ua/1/
I have a button called "Add" which relates to each person in a list.
echo <td><input type=\"submit\" id=\"PlayerAdded".$id."\" value=\"Add\"
onclick=\"add('".$id."','".$name."','".$_SESSION['GameID']."');\"></input></td>";
When "Add" is clicked, I want to add the persons details to a table (working fine), and also add a new row including their name and ID into a table in my DB (this is my problem).
I am aware that PHP won't work in a JS function. I'm also aware that I should never access the database on my site from JS due to the security issues.
So how can I have a button which onclick calls a function which adds to the database?
I tried writing my function in PHP, but it wasn't doing anything when I clicked the button. See my function below:
function add(id,name,game){
var t = ("</td><td>");
var str = ("<tr id='Players" + id + "'><td>")
var ctr = ("</td></tr>")
var PID = ("<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id)
var Pnam = ("<input type='hidden' name='Name" + id + "' value='" + name + "'></input>");
var place = ("<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>")
var points = ("<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>");
var cash = ("$<input name='Cash" + id + "' placeholder=' 0'></input>");
var ticket = ("<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>");
var del = ("<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>")
$('#PlayerAdded').before(str+ PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// This is where I want to insert into the db. Similar to
// <?php
// $sql = "INSERT INTO results (`col`, `col2`, `col3`) VALUES ('$id', '$name', '$game')";
// mysqli_query($dbcon,$sql); ?>
//but I want to be able to do it inside this java script function.
}
Remove the bracket before the variables, which you have written for every variable in function.
Add the ajax piece at the end of your function code.
function add(id, name, game) {
var t = "</td><td>";
var str = "<tr id='Players" + id + "'><td>"
var ctr = "</td></tr>"
var PID = "<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id;
var Pnam = "<input type='hidden' name='Name" + id + "' value='" + name + "'></input>";
var place = "<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>";
var points = "<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>";
var cash = "$<input name='Cash" + id + "' placeholder=' 0'></input>";
var ticket = "<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>";
var del = "<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>";
$('#PlayerAdded').before(str + PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// making ajax call to insert.php and posting the data
$.ajax({
method: "POST",
url: "insert.php",
data: {
"id": id,
"name": name,
"game": game
},
beforeSend:function(){
// show something before data is saved to db.
}
}).done(function(msg) {
$("body").append(msg); //debugging purpose
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
insert.php
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
$id= $_POST['id'];
$name= $_POST['name'];
$game= $_POST['game'];
//write your connection logic
// never write bare queries there is a chance of sql injection.
//Instead use prepared statement, prepare your query then bind the above values to it, then excute.
//write your insert logic below.
}
?>
You need to post the values you want to insert to your database via AJAX, append this to your add() function:
$.post('insertnew.php', { id:id,name:name,game:game }, function(data){
alert(data);
});
insertnew.php:
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
// sanitize your data here, then:
$id = $_POST['id'];
$name = $_POST['name'];
$game = $_POST['game'];
//connect to your db, or instead include your dbconnect.php
$link= new mysqli('localhost', 'my_user', 'my_password', 'world');
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//use prepared statement, prepare your query then bind the above values to it, then excute
$stmt = mysqli_prepare($link, "INSERT INTO results VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, $id, $name, $game);
if(mysqli_stmt_execute($stmt)){
echo "Record has been added successfully";
}else{
echo "Sorry, record could not be inserted";
}
}
?>
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/mysqli-stmt.bind-param.php
I am trying to replace content in a div after it has been saved to the db without reloading the page. When I click the save buttons the edit window disappears however the post wont get updated until I reload the page. Each post is build by following template and there are multiple posts.
var formatPost = function(d) {
var s = '';
s = '<div class="postWrapper" data-id="' + d.post_id + '"><h2 class="postHeading">' + d.title + '</h2>';
s += '<div class="postBody"> <p>' + d.body + '</p> </div>';
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '<div class="btn deleteButton">Delete</div>';
s += '</div>'
return s;
};
The following function is run when the edit button is pressed
function(data) {
var editableText = '<div class="editPostContainer" data-id="' + data.post_id + '">'
editableText += '<input type="text" class="editPostHeader" value="' + data.title + '">';
editableText += '<textarea class="editPostText">' + data.body + '</textarea>';
editableText += '<div class="btn saveEditButton">Save</div>';
editableText += '<div class="btn cancelButton">Cancel</div>';
editableText += '</div>';
$(self).parent().append(editableText);
}
When I click the save button following code is run
$.post(settings.server, {
saveID: $(this).parent().data('id'),
title: $('.editPostHeader').val(),
body: $('.editPostText').val()
}, function(data){
$(this).parent().siblings('.postHeading').text(data.title);
$(this).parent().siblings('.postBody').text(data.body);
});
And finaly the PHP that deals with the DB during this.
function save_post($id, $title, $body)
{
global $link;
$sql = "UPDATE post SET title= '$title',body= '$body' WHERE post_id= $id";
mysqli_query($link, $sql);
$sql = 'SELECT * FROM post WHERE id=' . $id;
$result = mysqli_query($link, $sql);
$saveResult = mysqli_fetch_assoc($result);
print json_encode($saveResult);
}