Stop page refresh on button click - php

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

Related

Updating Database and Page Content at the Same Time

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

Refresh div contents without closing dropdown

I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.

Link is cut after question mark in dynamic php table

I have a PHP dynamic table, and when I click on one of my link (http://www.xxxxxx.com/?r=xxxxxxxxx), the link open in a new tab and it's cut after the question mark (?), like www.xxxxxx.com/?.
Here is the table php code:
echo '<div class="row"><tr>';
echo '<td><form action='.$data['referral'].'>
<input class="btn" type="submit" formtarget="_blank" value='.$data['webadress'].' data-value='.gmdate("H:i:s",($data['timer']*60+60)).' data-start="false"></form></td>';
echo '<td>Now</td>';
echo '<td>'.$data['timer'].'</td>';
echo '<td>'.$data['payout'].'</td>';
echo '</tr></div>';
In my database, the $data['referral'] are my www.xxxxxx.com/?r=xxxxxxxxx link's.
I think is the type or something in my database option is wrong, so it cut after the question mark. Now I'm on varchar(255) and latin1_general_ci.
EDIT: I have put an input because I need store data for a timer, here is the JS:
$(window).load(function(){
var row = document.getElementsByClassName("color");
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
function redColor(element) {
$(element).css('background-color', 'rgba(255,0,0,0.7)');
}
function normalColor(elemen) {
$(element).css('background-color', 'transparent');
}
$('.btn').on('click', startTimer);
function startTimer() {
var dataStartElem = $(this);
var dataStart = dataStartElem.attr('data-start');
if (dataStart === 'false') {
dataStartElem.attr('data-start', 'true');
var nextElem = dataStartElem.parents('td').next();
var duration = dataStartElem.attr('data-value');
var a = duration.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
setInterval(function () {
seconds--;
if (seconds >= 0) {
nextElem.html(toTimeString(seconds));
redColor(nextElem);
}
if (seconds === 0) {
nextElem.html('Now');
dataStartElem.attr('data-start', 'false');
clearInterval(seconds);
normalColor(nextElem);
}
}, 1000);
}
}
});
This JS, start the timer and put it in red, and after the "now" appear when is finish.
By using a GET form, you override the query part of the action. Either convert your form to a normal link, or put the query part of the URL in a hidden input.
As #Otto said, try to do it in way near to this:
echo '
<div class="row">
<tr>
<td>
' . htmlspecialchars($data['webadress']) . '
</td>
<td>Now</td>
<td>' . $data['timer'] . '</td>
<td>' . $data['payout'] . '</td>
</tr>
</div>
';
Here is the solution, thanks to all have help me to figured out: i think it's the form who dont take "?" on link, so i have changed it to a normal link and here we go.
echo '<div class="row">
<tr>
<td>
<a href="'.$data['referral'].'" target="_blank">
<input type="submit" value="'.htmlspecialchars($data['webadress']).'" data-value="'.gmdate("H:i:s", ($data['timer'] * 60 + 60)).'" data-start="false" class="btn" formtarget="_blank">
</a>
</td>
<td>Now</td>
<td>'.$data['timer'].'</td>
<td>' . $data['payout'] . '</td>
</tr>
</div>';

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.

Categories