Updating Database and Page Content at the Same Time - php

This is a tough one for me. a total of five documents involved in this process. I can't help but feel that I am over complicating this issue. I asked about this previously and THOUGHT I understood the issue, but then I tried to add a simple "loading" modal to the equation, and it broke. What's worse I can't get it working anymore. I have changed too much. Yes I know I should have backed it up, let's get past that. The one language I cannot change at all in this whole element is my DB language, which is MySql.
What I Want to Happen
Page loads all non-archived submissions. The data is structured so that some but not all data is displayed for each row. At least not until the user clicks the "more info" button. NOTE: THIS IS NOT THE PROBLEM BUT ONLY HERE BECAUSE I HAVEN'T BUILT THIS YET, I WILL FOCUS ON THIS LATER.
After the user has finished using the data from one row, I would like the user to be able to archive the data into the database by changing the "archived" field from 0 to 1. After that is accomplished, I would like the row to disappear. If there is a lag and more than a second or two is needed to accomplish this, then a loading modal should appear that will indicate that the page has received the request and prevents the user from pressing the "archive" button multiple times.
What is Happening Now
When the page loads, all non-archived data is displayed in rows that show some but not all information for each record in a table. When the user clicks the "more info" button nothing happens. Note: Again I am not focusing on this issue I know how to fix this. When the user clicks on the "archive" button, it does nothing, but if they click if multiple times it eventually will bring up the "loading" modal and then refresh the page. The row that should have disappeared is still there, and the record still shows a "0" instead of a "1" as it should.
Final Comments Before Code Is Given
I am open to using other languages as I am a fast learner, I just don't know how to integrate them. But if you do respond with that, please also explain why my way is inferior and what I would have to do to make this work. I am still learning AJAX (very much beginner) and PHP (intermediate . . . I think).
The Code
index.php - abridged without head
<div class="container">
<h1><span class="hidden">Locate My Pet</span></h1>
<h2>Administration</h2>
<p class="lead alert alert-info">Hello There! You can review and archive submitted requests here.</p>
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="text-center">Submissions</h2>
</div><!--/.panel-heading-->
<div id="results"></div><!--To be populated by script-->
</div><!--/.panel .panel-default-->
</div><!-- /.container -->
<footer class="footer">
<div class="container">
<p class="text-muted text-center">© 2016 TL Web Development and Design</p>
</div><!--/.container-->
</footer><!--/.footer-->
<div class="modal fade" id="archiveMessage" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Archiving Submission</h4>
</div><!--/.modal-header-->
<div class="modal-body">
<p>Please wait . . .</p>
</div><!--/.modal-body-->
</div><!--/.modal-content-->
</div><!--/.modal-dialog-->
</div><!--/.modal-->
submission.php
<table class="table table-responsive table-striped">
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>Contact</th>
<th>Pet Info</th>
<th>Tools</th>
</tr>
<?php
require "../_php/connect.php";
$get_all = "SELECT request_id, fName, lName, address, city, state, zip, pPhone, cPhone, email, pName, gender, spayedNeutered, howLost, comments, timeEntered, archived FROM requests";
$result = $conn->query($get_all);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if (!$row['archived']) {
echo "<tr id='" . $row['request_id'] . "' class='fade in'>
<td>
" . $row['fName'] . " " . $row['lName'] . "</br>
<strong>Sent: </strong>" . $row['timeEntered'] . "
</td>
<td>" . $row['address'] . "</br>" . $row['city'] . " " . $row['state'] . ", " . $row['zip'] ."</td>
<td>
<strong>Primary Phone:</strong> <a href='tel:" . $row['pPhone'] . "'>" . $row['pPhone'] ."</a></br>
<strong>Cell Phone:</strong> <a href='tel:" . $row['cPhone'] . "'> " . $row['cPhone'] . "</a></br>
<strong>Email:</strong> <a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a></td>
<td>
<strong>Pet Name:</strong> " . $row['pName'] . "</br>
<strong>Gender:</strong> " . $row['gender'] . "</br>
<strong>Spayed or Neutered?:</strong> ";
if ($row['spayedNeutered'] = 0) {
echo "No</td>";
} else {
echo "Yes</td>";
}
echo "<td>
<button class='btn btn-info'>More info</button></br>
<form action='../_php/archive.php' method='get'><input type='hidden' value='" . $row['request_id'] . "' id='row_id'><button type='submit' class='btn btn-warning archive'>Archive</button></form>
</td>
</tr>";
}
}
} else if ($conn->connect_error != NULL) {
echo "<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>";
} else {
echo "<tr><td colspan='5'><div class='alert alert-info' role='alert'>No Records were found.</div></td></tr>";
}
?>
<script type="text/javascript" src="../_js/query.js"></script>
</table>
connect.php - some content no included for security reasons
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>)");
}
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$(".archive").click(function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
});
});
});
functions.php
<?php
require "connect.php"; // Connect to database
function archive($id) {
require "connect.php";
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['callArchive'])) {
archive($_POST['callArchive']);
} else {
archive(1);
}
?>

Since archive button is dynamically loaded, its the best choice to use .on('click') rather than .click() that does not fires on a dynamically loaded element. Try to read the question and answeres here, specially the selected correct answer.
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$("#results .archive").on("click",function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
//If you dont want to change your functions.php file use the commented line below instead of the above code
//data: {'callArchive':id},
});
});
});
When the user clicks on the "archive" button, it does nothing, but if
they click if multiple times it eventually will bring up the "loading"
modal and then refresh the page. The row that should have disappeared
is still there, and the record still shows a "0" instead of a "1" as
it should.
Since your ajax call data contains post 'archive' in which the value is id and you want to update some data of your request table but you are checking the wrong index of the POST data(if (isset($_POST['callArchive'])) ) rather change it to if (isset($_POST['callArchive']))
<?php
function archive($id) {
require "connect.php";// Connect to database
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['archive'])) {
archive($_POST['archive']);
} else {
archive(1);
}
?>
Hope that helps :D

Related

How to output a mysql row by using Ajax?

How can i get the whole row based on div ID(or something like this) using Ajax?
<div id="1">something inside</div>
<div id="2">something inside</div>
<div id="3">something inside</div>
<div id="4">something inside</div>
<div id="5">something inside</div>
<div id="6">something inside</div>
<div id="results"></div>
If someone clicks on a div, a row with the same id should be shown from the mysql.
When someone clicks on the <div id="3">, it should load a row, with the id "3" from mysql into the result div.
So far i was only able to code this:
$("#smash").click(function(){
$.ajax({
url: "loaditems.php",
success: function(result){
$("#items").html(result);
}});
});
PHP
<?php
include "mysql.php";
$sql = "SELECT * FROM SmiteItems";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='item'>";
// Name
echo "<h3>" . $row["name"] . "</h3>";
// DIV INFO
echo "<div class='info'>";
// Picture
echo "<img src='img/" . $row["id"] . ".png'>";
// Table Values
echo "<table>";
// Power
if($row["power"]>0) {
echo "<tr><td>Power:</td><td> " . $row["power"] . "</td></tr>";
}
// Attack Speed
if($row["attspeed"]>0) {
echo "<tr><td>Attack speed:</td><td> " . $row["attspeed"] . "</td></tr>";
}
// Lifesteal
if($row["lifesteal"]>0) {
echo "<tr><td>Lifesteal:</td><td> " . $row["lifesteal"] . "</td></tr>";
}
// Penetration
if($row["penetr"]>0) {
echo "<tr><td>Penetration:</td><td> " . $row["penetr"] . "</td></tr>";
}
// Physical Def
if($row["physdef"]>0) {
echo "<tr><td>Physical:</td><td> " . $row["physdef"] . "</td></tr>";
}
// Magical Def
if($row["magdef"]>0) {
echo "<tr><td>Magical:</td><td> " . $row["magdef"] . "</td></tr>";
}
// Health
if($row["health"]>0) {
echo "<tr><td>Health:</td><td> " . $row["health"] . "</td></tr>";
}
// HP regen
if($row["hp5"]>0) {
echo "<tr><td>HP5:</td><td> " . $row["hp5"] . "</td></tr>";
}
// Movement Speed
if($row["mspeed"]>0) {
echo "<tr><td>Movement:</td><td> " . $row["mspeed"] . "</td></tr>";
}
// Cooldown
if($row["cdown"]>0) {
echo "<tr><td>Cooldown:</td><td> " . $row["cdown"] . "%</td></tr>";
}
// Mana
if($row["mana"]>0) {
echo "<tr><td>Mana:</td><td> " . $row["mana"] . "</td></tr>";
}
// MP5
if($row["mp5"]>0) {
echo "<tr><td>MP5:</td><td> " . $row["mp5"] . "</td></tr>";
}
// Crowd Control Reduction
if($row["ccr"]>0) {
echo "<tr><td>CCR:</td><td> " . $row["ccr"] . "</td></tr>";
}
// Stack YES output
if($row["stack"]==1) {
echo "<tr><td>Stack:</td><td> Yes</td></tr>";
}
// Item Type Aura Passive etc
if (!empty($row["itype"])){
echo "<tr><td>Type:</td><td> " . $row["itype"] . "</td></tr>";
}
// Table Close
echo "</table>";
// Item description
if (!empty($row["text"])){
echo "<div class='text'>";
//echo "<h4>Description:</h4>";
echo "<p>" . $row["text"] . "</p>";
echo "</div>";
}
echo "</div>"; // CLOSE DIV INFO
echo "</div>";
}
} else {
echo "<p>0 results</p>";
}
$conn->close();
?>
I know that my PHP isn't great, i just started learning it. There are also empty rows in my MySQL table, so i need to check if it's empty before adding it to the html.
First you need an onclick event on the divs. When a div is clicked, their id will be passed to the getrow() function.
<div id="1" onclick="getrow(this.id)">something inside</div>
<div id="2" onclick="getrow(this.id)">something inside</div>
<div id="3" onclick="getrow(this.id)">something inside</div>
<div id="4" onclick="getrow(this.id)">something inside</div>
<div id="5" onclick="getrow(this.id)">something inside</div>
<div id="6" onclick="getrow(this.id)">something inside</div>
<div id="results"></div>
Here is the getrow() function. The div id is passed through the variable divid and sent to loaditems.php
function getrow(clicked_id) {
$.ajax({
url: "loaditems.php",
data: {divid: clicked_id},
success: function(data){
$("#result").html(data);
}
});
}
Then just change your PHP query like this (presuming each row is represented by an incrementing ID). I have written this in PDO as this is what you should be using to keep your site secure.
$sql = $conn->("SELECT * FROM SmiteItems WHERE ID=:rowid");
$sql->bindParam(':rowid', $_POST['divid']);
$sql->execute();
if($sql->rowCount() > 0) { // if a row is returned
while($row = $sql->fetch()) {
// rest of your code
}
}
First you'll need a function call on an event such as onclick on each div
<div id="1" onclick="getresult(1)">something inside</div>
<div id="2" onclick="getresult(2)">something inside</div>
<div id="3" onclick="getresult(3)">something inside</div>
<div id="4" onclick="getresult(4)">something inside</div>
<div id="5" onclick="getresult(5)">something inside</div>
<div id="6" onclick="getresult(6)">something inside</div>
<div id="results"></div>
Then use ajax in the function to fetch results from the PHP file and display it into the results div
function getresult(id){
var xhr= new XMLHttpRequest();
var params = "id="+id;
var url = address of your php file
xhr.open('POST',url,true);
xhr.onload=function(){
if(this.status == 200)
var resultarray = json_decode(this.responseText);
//now you can access the data like an array in the variable resultarray and display it however you wish
}
xhr.send(params);
}
In the PHP file get the id using POST variable and execute your mysql query.
require('mysql.php');
$stmt = $con->prepare("SELECT * FROM SmiteItems WHERE id=?");
$stmt->bind_param("i",$id);
$id=$POST['id']; //get the id from post variable
$stmt->execute();
$result=$stmt->get_result();
echo json_encode($result);

Stop page refresh on button click

I'm currently developing a system for internal use within my company to allow our service desk team to unlock user accounts/reset passwords.
I've completed the PHP/POST functions for this and have included them with the .load function on the dashboard of my system. This works and the function in question is LDAP account unlocks. The button is clicked, the post form is submitted and it all works fine. However it refreshes the entire page when submitted even though its been loaded via jQuery. I'm struggling to understand why this would happen, and how I can avoid it so I can give the end user successful or unsuccessful messages on button clicks. This is the main aim and is why I have started using JS load functions as I believed this would allow me to do so.
I'm entirely new to jQuery/JSON/JS and if this question is slightly in-descriptive or has an obvious answer apologies.
EDIT:
The way I have included the form is as such:
<div id="lockedout"></div>
<script>
$(document).ready(function(){
$("#lockedout").load('/modules/active-directory/includes/lockedout.php');
});
</script>
And the included form is:
<?php
set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
include ('/core/system/global.ldap.php');
$attributes = array("displayname", "mail", "samaccountname", "lockoutTime");
$filter = "(&(objectClass=User)(lockoutTime>=1)(title=*))";
$search = ldap_search($ldap_conn, $ldap_dn, $filter, $attributes) or die (ldap_error($ldap_conn));
$info = ldap_get_entries($ldap_conn, $search);
?>
<h4><i class="fa fa-lock"></i> Currently Locked Out (<?php echo $info["count"]; ?>)</h4>
<br>
<table class="table table-bordered">
<tbody><tr>
<th>Username</th>
<th>Unlock</th>
</tr>
<?php
for ($i=0; $i<$info["count"]; $i++) {
echo "<tr>";
echo "<td>" . $info[$i]["displayname"][0] . " (" . $info[$i]["samaccountname"][0] . ")</td>";
echo "</form><form method='post' action='/active-directory/' id='" . $info[$i]["samaccountname"][0] . "'></form>";
echo '<input type="hidden" name="dn" value="'. $info[$i]["dn"] .'" form="' . $info[$i]["samaccountname"][0] . '">';
echo "<td><center><button type='submit' id='unlock' name='unlock' class='btn btn-success btn-flat' form='" . $info[$i]["samaccountname"][0] . "'>Unlock </button></center></td>";
echo "</tr>";
}
?> </tbody></table>
This code is attached above the dashboard where i'm doing the JSON import.
<?php
if(isset($_POST['unlock']))
{
$attr["lockoutTime"] = "0";
$userdn = $_POST['dn'];
$result = ldap_modify($ldap_conn, $userdn, $attr);
echo '<script>
$(document).ready(function(){
$("#lockedout").load("/modules/active-directory/includes/lockedout.php");
});
</script>';
}
?>
if you want to submit content to backpage or verify users but not reload the entire page use AJAX.
if you want to simply show some alerts or validate form when you click the button use javascript or its derivatives

Using Ajax to get and show mysqli query results

I'm practicing Ajax by making an app that checks the content of a database table and inserts it into my page asynchronously, only the first row of the table is printing and I'm not sure why. This is my code:
index.php - Here is where I create the page with an empty space in #result_table that should get filled by the table fetched by places.php
<div class="row">
<div class="col-xs-3">
<button type="button" class="btn btn-lg btn-default" id="showPlaces" name="showPlaces">Mesas</button>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<table class="table table-striped">
<thead>
<tr>
<th>Nombre</th><th>Piso</th><th>Cliente</th><th>Mesero</th><th>Area</th><th>Estado</th>
</tr>
</thead>
<tbody id="result_table">
</tbody>
</table>
</div>
</div>
places.php - Here I make the query and return(?) the data
<?php
include("con.php");
mysqli_select_db("unicentaopos", $c);
$result = mysqli_query($c,"SELECT * FROM places");
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['FLOOR']."</td>";
echo "<td>". $places ['CUSTOMER']."</td>";
if (!$places['WAITER']) {
echo "<td>" . "VACIO" . "</td>";
} else {
echo "<td>". $places ['WAITER']."</td>";
}
echo "<td>". $places ['AREA']."</td>";
echo "<td>". $places ['ESTADO']."</td>";
echo "</tr>";
}
mysqli_free_result($result);
?>
script.js - Here I use jQuery to make the Http request
$( document ).ready(function() {
$('#showPlaces').click(function(){
$.ajax({
type:'GET',
url: 'places.php',
dataType: 'html',
success: function(result){
$('#result_table').html(result);
} // End of success function of ajax form
}); // End of ajax call
});
});
con.php - Here I connect to the database
<?php
$c = mysqli_connect("localhost","root","root","unicentaopos");// Check connection
if (mysqli_connect_errno()) { // Si hay error lo menciona en alerta.
echo '<div class="alert alert-danger">';
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
echo '</div>';
} else { // Si no hay error.
}
?>
I've been stuck on this for a while, could you guys help me pinpoint the problem? I guess it's either the way i'm returning the data from places.php, or I'm making a mistake in the connection, wich would be weird since that very same code worked for a simple example I did a while ago.
Please remember, I'm new to Ajax so anything you can tell me that helps me improve will be very welcome.
Fixed it with help of the comments and edited the post with the working code.

Triggering function from jQueryMobile "slide panel", "list view"

In my jQueryMobile app I'm using slider for search part of application. When slider is opened and user writes "word to search" into search panel, list view of found results is printed out in format:
<li><a id='$id'>***search result***</a></li>
its loaded from php search file. On click of this li part of list view I need to trigger onClick function redirecting into another page and create variable. But this onClick trigger is not being picked.
This is pannel with search init:
<div data-role="panel" data-theme="b" id="mypanel" data-position="right" data-position-fixed="true" data-display="overlay">
<input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
<div id="search_results">
<ul data-role="listview" data-divider-theme="b" data-inset="true" id="sub_cont"></ul>
</div>
</div>
Php which sends search result:
if($uname == $check_uname){
echo "<li id='search_r'>" . "<a href='#'>" . $uname . " : " . " " . $fname . " " . $sname . "</a>" . "</li>";
}else{
echo "<li id='search_r'>" . "<a href='#' id='$id' class='s_result'>" . $uname . " : " . " " . $fname . " " . $sname . "</a>" . "</li>";
}
and jQuery:
$("#cc_page").live('pageshow', function(){
$("#search_r").click(function(){
var search_r = $('.s_result').attr('id');
window.location.href = "http://imes.jzpersonal.com/app/userpanel.html#sfpp_page";
});
});
but still click function is not being triggered. Anyone same experience? Anyone found a correct working way?
Solution:
$("#cc_page").ready(function(){
$("#search_r").live('click', function(){
search_r = $(this).attr('id');
window.location.href = "http://imes.jzpersonal.com/app/userpanel.html#sfpp_page";
});
});
This is not going to work. From what you have explained when you enter "word to search" listview is dynamically populated with li items, same li items that should have a click event on them.
Here's a problem. You are binding a click event in the wrong moment. In your case click event is bind at a pageshow event, and at this point listview is not populated with search results and because of how javascript works future li elements are not going to have a click event on them. Event can not be bind retroactively.
What you should do is to bind a click event only after elements have been appended to a listview.

.load() little part without toggle

I have a conversations flow who is refresh with .load() of jQuery every 3 seconds.
This system work, but in each conversation I have an answer button who slide a form (textarea and submit button) with .toggle().
To display the flow, I use a while with PHP.
My issue is, when the is loading by .load(), and answer button is clicked, the form hide again and text contain too.
<div id="the_river_loading">
<?php
$sql_the_river = 'SELECT u.nickname, u.firstname, u.lastname, u.main_photo, u.locality,
id_conversation, id_messages, owner, participants, text, date
FROM users AS u
INNER JOIN the_river
ON u.nickname = owner
WHERE answer = 0
ORDER BY date DESC';
$result_the_river = mysqli_query($mysqli, $sql_the_river);
$count = 0;
while ($data_the_river = mysqli_fetch_assoc($result_the_river))
{
$count++;
echo '<div class="message_container_news">'; // Start block conversation
echo '<a href="/profile/' . $nickname . '" class="name_links" style="vertical-align: top; font-size: 16px;">
<img src="' . $main_photo . '" title="' . $name . '" class="members_actu_photo" />' . $name . '</a>
<span style="vertical-align: top">, ' . $locality . '</span><span style="float: right; font-size: 12px;">Posté le Octobre 25, 2012</span>
<p style="margin-top: 5px;">' . $data_the_river['text'] . '</p>
<div class="btnAnswer_nb">' . $count_answer . '</div> Answers
See conversation
<div class="btnAnswer_news" id="btnAnswer_news_id_' . $count . '">Reply</div>
<form method="post" id="display_form_id_' . $count . '" action="" style="display: none;">
<br />
<textarea name="answer_text"></textarea><br />
<input type="submit" name="answer_valid_id_' . $count . '" value="Post" />
</form>
</div>'; // End block conversation
}
?>
</div>
<script type="text/javascript">
$(".btnAnswer_news").live("click", function(){
var num_show = this.id.replace(/\D/g, "");
$("#display_form_id_" + num_show).toggle("fast");
});
var auto_refresh = setInterval(
function() {
$("#the_river_loading").load("/home" + " .message_container_news");
}, 3000
);
</script>
In pleasure of read you.
This is because if you load the content again into the container, the styles applied per js will get removed (because they were applied through style="" and this gets refreshed). You should move the Form and the Button to another Div, wich is not in the loading Div.
If I understand your problem correctly (you've not be very descriptive), you just want to not hide the form when clicking again, for that use show() instead of toggle() , so replace your following line:
$("#display_form_id_" + num_show).toggle("fast");
for this one:
$("#display_form_id_" + num_show).show("fast");
If you want to keep the text of the textarea, you can like so:
var auto_refresh = setInterval(
function() {
tx = $("#the_river_loading textarea[name='answer_text']").val();
$("#the_river_loading").load("/home" + " .message_container_news", function(){
$("#the_river_loading textarea[name='answer_text']").val(tx);
});
}, 3000
);

Categories