Hi everyone, I have 4 parts of my code
2 html buttons (Activate User, Delete User)
a html table
jquery on getting user_id on html table
php script in executing update or delete sql command
Scenario:
I have a html table (the data are pulled from the SQL DB using a php script) I can select the rows on the table and extract their user_id flawlessly but the problem is that I have these two buttons (Activate User, Delete User) everything works well until you put their codes together the problem is that the activate php script takes command and not the delete user script. Is their a "break;" on php scripts just like switch cases so that it won't execute the other instead it executes the script specifically for those two buttons.
These are my buttons
<a type="button" id="activateUser"> Activate Selected User</a>
<a type="button" id="deleteUser"> Delete Selected User</a>
This is the jQuery script for highlighting my html table row
<script>
$('tr').click(function ()
{
$('tr').removeClass('selected');
$(this).addClass('selected');
selectedRow = $(this);
});
This is the jQuery script for getting the id for my button and getting the user_id on Activate Selected User button.
$("#activateUser").click(function ()
{
var td = $(selectedRow).children('td');
for (var i = 0; i < 1; ++i) {
window.location.href = window.location.href+'?id='+td[i].innerText;
}
});
This is the jQuery script for getting the id for my button and getting the user_id on Delete Selected User button.
$("#deleteUser").click(function ()
{
var td = $(selectedRow).children('td');
for (var i = 0; i < 1; ++i) {
window.location.href = window.location.href+'?id='+td[i].innerText;
}
});
This is the PHP SCRIPT for activating the user by changing the user_active to 1 which activates the user
<?php
$id = $_GET['id']; //gets the user_id from as GET request
$btnQuery = "SELECT * FROM users WHERE user_id='$id'";
$buttonquery = mysqli_query($DBLink, $btnQuery);
$Actcount = mysqli_num_rows($buttonquery);
$act = 1;
if($Actcount == 1)
{
$sqlact = "UPDATE users SET user_active='$act' WHERE
user_id='$id'";
$activate = mysqli_query($DBLink, $sqlact);
if($activate)
{
echo $ActivatedUser = "<b>Success!</b> User successfully Activated.";
echo "<script>setTimeout(function()
{
window.location.replace('http://localhost/webpage/manage-user.php');
}, 1500);
</script>";
}
}
?>
This is the PHP SCRIPT for deleting the selected user
<?php
$id = $_GET['id'];
$btnQuery = "SELECT * FROM users WHERE user_id='$id'";
$buttonquery = mysqli_query($DBLink, $btnQuery);
delcount = mysqli_num_rows($buttonquery);
if($delcount == 1)
{
$sqldel = "DELETE FROM users WHERE user_id='$id'";
$delete = mysqli_query($DBLink, $sqldel);
if($delete)
{
echo $Deleted = "<b>Success!</b> User successfully Deleted.";
echo "<script>setTimeout(function()
{
window.location.replace('http://localhost/webpage/manage-user.php');
}, 1500);</script>";
}
}
?>
THE CODE STRUCTURE
[ACTIVATE USER] BUTTON
SCRIPT FOR SELECTING ROW IN HTML TABLE
SCRIPT FOR GETTING THE user_id FOR USER ACTIVATION
PHP SCRIPT ON ACTIVATING
[DELETE USER] BUTTON
SCRIPT FOR SELECTING ROW IN HTML TABLE
SCRIPT FOR GETTING THE user_id FOR USER DELETION
PHP SCRIPT ON DELETING
Again, it works well without the other half or vice versa, but when I try to combine them it never executes and it even executes only the first part or sometimes bugs. I tried using exit() or die() at the end of each php script but it makes matters worst.
Thanks Everyone.
You need to add a parameter to your URL that indicates which action you want:
$("#activateUser").click(function ()
{
var td = $(selectedRow).children('td').first();
window.location.href = window.location.href+'?action=activate&id='+$(td).text();
}
});
$("#deleteUser").click(function ()
{
var td = $(selectedRow).children('td').first();
window.location.href = window.location.href+'?action=delete&id='+$(td).text();
}
});
Then in your PHP script you check $_GET['action']:
if ($_GET['action'] == 'activate') {
// code for activating account
} elseif ($_GET['action'] == 'delete' {
// code for deleting account
} else {
die("Invalid action");
}
Related
Edit: Im using XAMPP with built in Apache, vscode
I make a live search input(html>js>php>js>html) , it run smoothly at first key-in, but it's getting slower and slower when i delete and key-in again , wonder what's causing the delay and how to fix it.
And i have a question,
For this example , it is better to use jquery or pure javascript?
Thank you
html
<div>
<input type="text" class="search" placeholder="find..." autocomplete="off" autocapitalize="characters">
<div class="result"></div>
</div>
js
$(document).ready(function(){
$(document).on("keyup input",".search",function(){
var input = $(this).val();
var result = $(this).next(".result");
if(input.length){
$.get("table.php", {term: input}).done(function(data){
result.html(data);
});
} else{
result.empty();
}
});
});
php
<?php
$link = mysqli_connect("localhost", "root", "******", "crypto");
// Check connection
if($link === false){
die("ERROR: " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
$coin = "show tables from crypto where Tables_in_crypto LIKE ?";
//prepare the statement
if($prepare = mysqli_prepare($link, $coin)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($prepare, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($prepare)){
$result = mysqli_stmt_get_result($prepare);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["Tables_in_crypto"] . "</p>";
}
} else{
echo "<p>no result</p>";
}
} else{
echo "ERROR: $coin. " . mysqli_error($link);
}
}
// Close statement
mysqli_stmt_close($prepare);
}
// close connection
mysqli_close($link);
?>
<script type="text/javascript" src="data.js"></script>
JavaScript
Don't use "keyup input", use just the "input" Event.
Trim $(this).val().trim() your input values, you don't want an empty space to trigger a search for data!
Cooldown! You don't want to perform an additional AJAX ($.get()) request while one is already on the way. Instead create a setTimeout throttle which - only once the user stopped typing for N milliseconds the request will be triggered.
A pseudocode logic to picture it is quite simple:
jQuery($ => { // DOM ready and $ alias in scope
const search = ($input) => {
const input = $input.val().trim(); // Trim your strings!
const $result = $input.next(".result");
if (!input) {
$result.empty();
return; // end it here
}
$.get("table.php", {term: input}).done((data) => {
console.log(data);
// Exercise for the reader:
// Make sure data is an Object
// create "<p>" elements with text and populate $result
});
};
let searchCooldown; // Search input cooldown
$(document).on("input", ".search", function() {
clearTimeout(searchCooldown); // clear occurring search timeout
searchCooldown = setTimeout(() => {
search($(this)); // will be triggered once user stops typing for 300ms
}, 300); // 300ms seems like a good typing timeout?!
});
});
No, you don't need jQuery. The Fetch API is mature enough.
PHP
Don't place <script> tags inside a PHP file — which its only job should be querying the data from a database and returning it.
Don't return HTML from PHP! That's a waste. You might want a PHP file to return JSON data instead - that way it can be used by your HTML page, your watch, fridge, etc. It's usually done using echo json_encode($result);. If you need to attach also an "error" property to your $result data JSON, do so.
I don't deserve a credit for myself because everything i find mainly is on stackoverflow (after many hours spent) just I model everything to my own needs and like to give back in return.
If your page has no pagination a nice and easy way to live search all the items in javascript by doing the following (the html code may not be related to the script):
-you need to use XPath in chrome dev tools, to get the element needed:(right click on an element node->Copy -> copy full xpath)
-lets say we want to search for all the <h2> text tags inside :
-in blade file we have products.blade.php:
<html>
<body>
<input type="text" placeholder="search" id="search" onkeyup="myFunction()"></input>
<ul id="myList" class="myList-class">
<li><h2>item 1<h2></li>
<li><h2>item 2<h2></li>
</ul>
//the script below is not related to the tags above, but just to give you an idea.
<script>
function myFunction() {
var lis = document.querySelectorAll('.columns-3.products.snip-ul > li');//get all the <li> tags, change it to your needs(get the value from Ranorex selocity extension in chrome).
var x = document.getElementById("search").value; //item to search for(textbox)
if (document.getElementById("search").value.length == 0) { //if nothing is typed in textbox get all the products back
lis.forEach(node=>node.setAttribute("style","display:flex")); // restore all the display attribute to flex
return;
}
for (var i = 1; li = lis[i-1]; i++) {
var searchTitles = ((document.evaluate('/html/body/div[1]/ul/li[' + i + ']/div/div[2]/a/h2/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data);
//change the above xpath to your own needs : (document.evaluate('XPATH HERE', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data;
// li.parentNode.removeChild(li);
if (searchTitles.toLowerCase().includes(x.toLowerCase())) {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:flex";
} else {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:none"; //hide all <li> tags
}
}
}
</script>
I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();
I want my client side web to auto-refresh when data in my Database updated, when adding or deleting data I have succeeded however when the data changed, it still fails.
This is my code for checking data from database:
<script>
var row1 = "<?php echo $variable; ?>";
var processUpdate = function( response ) {
var x = response;
//console.log(x);
if (row1 != x) {
window.location.reload();
}
}
var checkUpdates = function() {
serverPoll = setInterval(function() {
$.get('check.php', { lastupdate: 1 }, processUpdate, 'html');
}, 1000)
};
$(document).ready(checkUpdates);
</script>
check.php:
$query = mysqli_query($koneksi, "SELECT * FROM table");
$number = mysqli_num_rows($query);
echo $number;
What should I change to be automatically refreshed if every data in the table is changed?
You can use trigger that will insert some info about each table update in another table, and then just query the num rows on 'changes' table in a similar way you check for new ones here:
DELIMITER //
CREATE TRIGGER table_update_trigger AFTER UPDATE ON table
FOR EACH ROW BEGIN
INSERT INTO table_history
(
change
)
(
NEW.some_value,
);
END
//
The advantage of this solution is you don't need to introduce/rely on/maintain any other db system like Redis and the checking code is not responsible for keeping and updating any counters and queries for updates, inserts and deletes in a similar fashion. Also you might extend the table_history table to log all the fields you are interested in in terms of tracking changes and end up having useful changelog for the purpose of the application.
I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.
I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.
UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.
Image Index Page:
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'] {
$_SESSION['Worksafe_Mode'] = 1;
}
?>
<!-- other page content -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- other page content -->
<button type="button" id="Worksafe_Button" name="Worksafe_Button">
Toggle Worksafe Mode
</button>
<script>
$('#Worksafe_Button').click(function() {
$.post("worksafe_mode_toggle.php")
.done(function(data) {
window.location.href = window.location.href;
});
});
</script>
<!-- other page content -->
<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');
while($row = mysqli_fetch_assoc($image)) {
if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
echo 'If you are over 18, toggle Worksafe Mode to view this image';
}
else {
echo '<img alt="'.$row['title'].'" src="../'.$row['uri'].'/s.jpg" srcset="../'.$row['uri'].'/m.jpg 2x">';
}
}
?>
worksafe_mode_script:
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 1) {
$_SESSION['Worksafe_Mode'] = 0;
}
else {
$_SESSION['Worksafe_Mode'] = 1;
}
}
I think ajax is a good approach in your case.
I might do something like display a page of SFW images as the default, along with the toggle button.
When they click the button it triggers an ajax request to the back-end that sets/un-sets the session value in toggleWorksafe.php. Finally it triggers a page refresh.
During the page refresh the PHP code checks whether the session variable is set and shows either the filtered or unfiltered set of images, and changes the button's text to match.
To implement:
Include jQuery in the <head> section (jQuery simplifies the ajax call):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'])) {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
<button id="workSafe" type="button" name="Worksafe_Toggle_Button">
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo 'Hide NSFW images';
}
else {
echo 'Include NSFW images';
}
?>
</button>
<!-- display safe images by default -->
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo '<br/><br/>Showing NSFW images';
}
else {
echo '<br/><br/>Showing safe images only';
}
?>
<!-- any other page content here -->
<script>
$('#workSafe').click(function() {
// ajax request to page toggling session value
$.post("/toggleWorksafe.php")
.done(function(data) {
window.location.href = window.location.href; // trigger a page refresh
});
});
</script>
</body>
</html>
toggleWorksafe.php:
<?php
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 'yes') {
$_SESSION['Worksafe_Mode'] = 'no';
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
there are a couple of ways to do this and it related to how you hide or load you images.
1. simple method
if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:
var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false
function loadImage(nsfw){
if (nsfw){
$.get('nsfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
} else {
$.get('sfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
}
}
and in you button click event:
nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);
2. another simple method, but not as simple as the #1
you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.
note: this method still uses cookie
for example the returned list is like this:
[
{"url": "some-image-1.jpg", "nsfw": "true"},
{"url": "some-image-2.jpg", "nsfw": "false"},
{"url": "some-image-3.jpg", "nsfw": "true"},
{"url": "some-image-4.jpg", "nsfw": "false"},
{"url": "some-image-5.jpg", "nsfw": "false"},
{"url": "some-image-6.jpg", "nsfw": "true"}
]
then you just render it when the conditions are met.
function renderImage(nsfw){
$.get('image-list-url', function(resp){
list.forEach(function(val, key){
if (nsfw || !val.nsfw){
$('#container').append('<img src="' + val.url + '/>');
}
});
});
}
and many other methods that are too long to explain, such as using Angular, React, or Vue
still uses cookie for between reloads or backs, and does not regard user's age.
as for the session based approach, you only need that if you need to verify your users age
that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use #KScandrett 's answer
Confirm form resubmission happens because you do not perform a redirect after a successful form submission.
Take a look at this wiki page to see how to do it right. https://en.wikipedia.org/wiki/Post/Redirect/Get
I have been able to get my button to download the file (html canvas), but I need it to also increment a SQL field by one.
I am not sure how much code you will need, so I will begin by giving you the parts I am trying to get to talk to each other.
PHP:
$insert = mysql_query("update UserName set logins = logins+1 where password='$password' AND username='$username'", $connection);
HTML Button:
<div>
<a id="dload" download="YourFileName.png">Download as image</a>
</div>
JAVA (On the same page as button)
function download() {
var dt = c5.toDataURL("image/png", 1.0);
this.href = dt;
};
function insert(){
var insert = <?php $insert; ?>;
};
dload.addEventListener('click', download, false);
dload.addEventListener('click', insert, false);
The PHP code lives on a file called login.php as a variable. Login.php is included on the file that contains the HTML button and Java above.
The download part works. The SQL query is correct and works when run on the database. But I am just not sure how to integrate so it both downloads and adds one to the database.
Thanks for looking.
EDIT:
I can now get it to do both, but now it only increments the SQL field once per logon (will download every time though). The user needs to logout , then log back in for it to work properly again. I need it to increment by one every time they click download.
I changed this:
function download() {
var dt = c5.toDataURL("image/png", 1.0);
this.href = dt;
};
function insert(){
var insert = <?php $insert; ?>;
};
dload.addEventListener('click', download, false);
dload.addEventListener('click', insert, false);
to this (which is what I had originally):
function download() {
var dt = c5.toDataURL("image/png", 1.0);
this.href = dt;
};
dload.addEventListener('click', download, false);
And changed my button to this:
echo <a id="dload" download="YourFileName.png" value="<?php echo $insert; ?>">Download as image</a>