I have a page using JqueryUI Mobile. More specifically it uses JqueryMobile Lists
http://demos.jquerymobile.com/1.2.1/docs/lists/lists-ul.html
I love the look, feel, and usage of the listview, but I have come into a problem.
The users need to be able to click the link quickly, which is difficult with how I do it now. The link performs a PHP function, then redirects back to page they was on and the cycle restarts. Now that I am getting more familiar with AJAX, I would like to be able to have them click the link, it updates the database, then calls my AJAX script to update the data without the refreshing the page.
This would enable the users to be much much quicker with the tasks as most of the down time they have currently is the few seconds it takes to refresh (or more accurately be redirected back to) the page. When if its possible they would like to be able to click a link every second or even more if they are able to.
My question is: How can perform a database update based on dynamically generated links from a MySQLi database without requiring the user to refresh? I believe once I have that, I could also use Ajax to update the list every quarter second or so. I've considered using buttons, but I'm not sure how that would tie into listview, since listview seems to be only based on links.
On a side note - are their standard practices with often Ajax should update? Is there any guidelines I should follow?
Here is a sample of my current code:
<?php
session_start();
if(isset($_SESSION['username']))
{
}
else
{
$_SESSION['error']="You are logged in.";
header('Location: index.php');
exit;
}
?><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/> <!--320-->
<link rel="stylesheet" href="js/jquery.mobile-1.4.5.min.css">
<script src="js/jquery-1.11.3.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="js/jquery.mobile-1.4.5.min.js"></script>
<style>
.split-custom-wrapper {
/* position wrapper on the right of the listitem */
position: absolute;
right: 0;
top: 0;
height: 100%;
}
.split-custom-button {
position: relative;
float: right; /* allow multiple links stacked on the right */
height: 80%;
margin:10px;
min-width:3em;
/* remove boxshadow and border */
border:none;
moz-border-radius: 0;
webkit-border-radius: 0;
border-radius: 0;
moz-box-shadow: none;
webkit-box-shadow: none;
box-shadow: none;
}
.split-custom-button span.ui-btn-inner {
/* position icons in center of listitem*/
position: relative;
margin-top:50%;
margin-left:50%;
/* compensation for icon dimensions */
top:11px;
left:-12px;
height:40%; /* stay within boundaries of list item */
}
.ui-icon-delete:after{
background-color: #B22222 !important;
background-image:url("data:image/svg+xml;charset=US-ASCII,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22iso-8859-1%22%3F%3E%3C!DOCTYPE%20svg%20PUBLIC%20%22-%2F%2FW3C%2F%2FDTD%20SVG%201.1%2F%2FEN%22%20%22http%3A%2F%2Fwww.w3.org%2FGraphics%2FSVG%2F1.1%2FDTD%2Fsvg11.dtd%22%3E%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20%20width%3D%2214px%22%20height%3D%2214px%22%20viewBox%3D%220%200%2014%2014%22%20style%3D%22enable-background%3Anew%200%200%2014%2014%3B%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpolygon%20fill%3D%22%23FFF%22%20points%3D%2214%2C3%2011%2C0%207%2C4%203%2C0%200%2C3%204%2C7%200%2C11%203%2C14%207%2C10%2011%2C14%2014%2C11%2010%2C7%20%22%2F%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3Cg%3E%3C%2Fg%3E%3C%2Fsvg%3E")
}
.ui-icon-home:after{
background-color: #A2CD5A !important;
}
.ui-icon-arrow-u-r:after{
background-color: #3D59AB !important;
}
</style>
</header>
</head><center> <h2 style="">Empty For now<br><br>
</h2></center>
<a href="home.php" class="ui-btn ui-icon-home ui-btn-icon-left" data-ajax='false'>HOME</a>
<a href="ViewOrderMobile.php" class="ui-btn ui-icon-edit ui-btn-icon-left" data-ajax='false'>VIEW / EDIT CURRENT LINE</a>
<br><br><br><br>
<center><center>
<div data-role="main" class="ui-content"style="margin-top:-75px;">
<h2 style=""></h2>
<ul data-role="listview">
<?php
include "../../includes/databaseconnections/demo/database_connection.php";
///////////////////////////////////////////////////////////////////////////////////////////////
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else{}
$query = "SELECT * FROM Table1 LEFT JOIN Table2 USING (ID) WHERE Table1.feild1 = '0' ORDER BY dateSelected ASC LIMIT 25";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
if ($row['photoLink'] == NULL)
{
$row['photoLink'] = "endofgroup";
$row['lastName'] = "End Of Group " ;
$ID = "&ID=".$row['ID'];
}
if ($row[leftGym] == "1") { $flash = "style='color:#B22222;font-size:140%'";} else {$flash ="";}
echo "<li><a href='button1.php?sid=${row['ID']}' $flash style='font-size:140%;' width='25px' data-ajax='false'> {$row["lastName"]}, {$row["firstName"]} ({$row["pmBusNumber"]})</a><div class='split-custom-wrapper'>
<a href='button2.php?sID={$row['ID']}&lane=1{$ID}' data-role='button' class='split-custom-button' data-icon='delete' data-rel='dialog' data-theme='c' data-ajax='false' data-iconpos='notext'></a>
</div></li>";
}
/* free result set */
mysqli_free_result($result);
}
mysqli_close($link);
/////////////////////////////////////////////////////////////////////////////////
?>
</ul><br>
</div>
</div>
</div>
</body>
</html>
I've added comments to the code snippet. Please let us know if you require further info.
Based on jquery ajax() v3.1.1
html: update the a element in the list with class=myCustomClass
<a href='button1.php?sid=${row['ID']}' $flash style='font-size:140%;' width='25px' data-ajax='false' class='myCustomClass'> {$row["lastName"]}, {$row["firstName"]} ({$row["pmBusNumber"]})</a>
<div class='split-custom-wrapper'>
<a href='button2.php?sID={$row['ID']}&lane=1{$ID}' data-role='button' class='myCustomClass split-custom-button' data-icon='delete' data-rel='dialog' data-theme='c' data-ajax='false' data-iconpos='notext'>
</a>
</div>
<span id="status"></span>
script :
$(function () {
//Attach the click event to Links only with class=myCustomClass and perform this function
$("a[class=myCustomClass]").on('click', function (e) {
e.preventDefault(); //preven the page from navigating, the default behaviour for a link
$.ajax({
url : this.href, //perform a ajax request with the link, GET in this case
/* type: POST, */
beforeSend : function () {
$("#status").text('Working..')
}
}).done(function (data) {
console.log(data); //do something with the data if any
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("ERROR"); //report in console for errors
console.info(jqXHR);
console.info(textStatus);
console.info(errorThrown);
}).always(function () {
//do this step every time
$("#status").text('completed..')
console.info("completed"); irrespective of result
});
})
Related
I am working on a simple web page that stores the start time, then displays the time when you click a button sort of like a timer. I came across this problem where when clicking a button in a form, it reloads the script overwriting the start time variable. Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Work Tracker</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {background-color: grey;}
.button {
border: none;
color: rgb(0, 0, 0);
padding: 15px 32px;
text-align: right;
text-decoration: none;
display: inline-block;
font-size: 25px;
margin: 4px 2px;
cursor: pointer;
border-radius: 10px;
}
.button2 {background-color: #ff0000;}
#text1 {
color: black;
text-align: center;
font: bold 24px sans-serif;
background: white;
padding: 10px;
border: solid black 2px;
border-radius: 10px;
}
</style>
</head>
<body>
<?php
date_default_timezone_set('America/Los_Angeles');
$startTime = date("h:i a");
echo "<h2>" . $startTime . "</h2>";
if (isset($_POST["btn-endtimer"])) {
$endtime = date("h:i a");
echo "<h2>" . $endtime . "</h2>";
}
?>
<script type="text/javascript">
if(starttime === undefined){
var starttime = "<?php echo "$startTime"; ?>";
console.log(starttime);
}
console.log(starttime);
</script>
<form method="post">
<input type="submit" value="End Timer" name="btn-endtimer" style="background-color:#ffb3b3; height:100px; width:250px; font-size:50px; border-radius: 15px; border-color: #fc9f9f">
</form>
</body>
</html>
Here is the webpage:
it displays the time when the page was opened as well as a button. When this button is clicked, it runs a line of code that stores the current date, but it reloads the script, so the start time variable is overwritten to the current time. Is there a way to send the starttime variable somewhere so that it can not be changed? This is what is looks like after clicking the button a few minutes later:
Update: I have tried session variables, but it seems that the code jumps straight there. For example:
session_start();
echo $_SESSION['a'];
$_SESSION['a'] = "hello world"
echo $_SESSION['a'];
prints
hello world
hello world
Why?
Perhaps the easiest way to interact between browser and server to do what you want
( log a time ) would be to use AJAX. Requests are sent without needing to reload the page and provide a better user experience.
The following would send a time to the server (same page in this instance) - how you deal with that server-side is not specified but would, in most cases, involve writing to a database.
This demo will fire an ajax request but due to the sandbox will throw an error but inspecting network traffic in console should illustrate what happens.
// utility to format a Date into a minimal timestring - chose UK for locale
const gettime=()=>Intl.DateTimeFormat('en-GB', { timeStyle:'medium' } ).format( new Date() );
// utility to display, in the H2 element, the time at any particular moment
const displaytime=()=>{
let date=gettime();
let content=`<div>${date}</div>`;
document.querySelector('h2').insertAdjacentHTML('beforeend',content)
};
// the AJAX callback. This can be used to do what ever you need to do once you have logged
// the time on the server. DOM manipulation, inform user, open window etc
const callback=(r)=>{
alert(r)
};
// There is no need to actually send the time from the client ( it can be modified )
// - instead you could just send a beacon to say "log now" type thing but for example
// send the time to the same page.
const sendtime=()=>{
let url=location.href; // or /path/to/script.php etc
let fd=new FormData();
fd.set('time',gettime() );
fetch( url,{ method:'post',body:fd } )
.then(r=>r.text())
.then(callback)
.catch(alert)
};
// delegated event listener to respond to button clicks
document.addEventListener('click',e=>{
if( e.target instanceof HTMLInputElement && e.target.type=='button' && e.target.name=='btn-endtimer' ){
displaytime();
sendtime();
}
});
// how initial load time - this could be fetched from db rather than using current time!
displaytime();
body {
background-color: grey;
}
/*
other styles removed as they were not applicable
to the original code
*/
input[name="btn-endtimer"] {
background-color: #ffb3b3;
height: 100px;
width: 250px;
font-size: 50px;
border-radius: 15px;
border-color: #fc9f9f
}
<h2></h2>
<input type="button" value="End Timer" name="btn-endtimer" />
The method post will always refresh the page since PHP code is sent to server and it needs to be loaded typically on new page.
You can avoid that by using JavaScript function
<body>
<?php
date_default_timezone_set('America/Los_Angeles');
$startTime = date("h:i a");
echo "<h2>" . $startTime . "</h2>";
?>
<script>
window.addEventListener("load", function() {
var endTime = "";
var startTime = "<?php echo $startTime; ?>";
console.log(startTime);
document.getElementById("end-timer-button").addEventListener("click", function() {
endTime = new Date().toLocaleTimeString();
document.getElementById("end-time").innerHTML = endTime;
});
});
</script>
<button id="end-timer-button"
style="background-color:#ffb3b3; height:100px; width:250px; font-size:50px; border-radius: 15px; border-color: #fc9f9f">End
Timer</button>
<h2 id="end-time"></h2>
</body>
The PHP code is used to create new variable $startTime and store it. The JavaScript code is used to handle the button click and store var = EndTime wich is an empty string that gets value from PHP $startTime. Finally document.getElementById("end-time").innerHTML = endTime; prints out the EndTime variable into <h2 id="end-time"></h2> if you want the time to be displayed above the button. you can simply put it between the PHP code And start of JavaScript like this
echo "<h2>" . $startTime . "</h2>";
?>
<h2 id="end-time"></h2>
<script>
Hope this helps / solves your problem
i've created 3 files. The main is html with javascript, the second one is based on php only and the third one uses html and inline php forms.
In main file, i've written the below script:
$(document).on('click', '.print_fumes_card', function(){
var user_id1 = $(this).attr("id");
alert(user_id1);
$.ajax({
url:"print/print_fumes_card.php",
method:"POST",
data:{user_id1:user_id1},
success:function(data)
{
window.open ("print/print_fumes_card.php","_blank");
}
})
});
The above script is enabled, only when i press the button '.print_fumes_card' in second php file.
The problem is that var user_id1 doesn't pass to third file (mix of html and php) "print_fumes_card.php" and i can't undertand why.
I need that variable in 3rd file to, execute some select queries.
The structure of thrid file is the following:
<!DOCTYPE html>
<?php
require 'conn.php';
echo $_POST["user_id1"];
?>
<html lang="en">
<head>
<style>
.table {
width: 100%;
margin-bottom: 20px;
}
.table-striped tbody > tr:nth-child(odd) > td,
.table-striped tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
#media print{
#print {
display:none;
}
}
#media print {
#PrintButton {
display: none;
}
}
#page {
size: auto; /* auto is the initial value */
margin: 10; /* this affects the margin in the printer settings */
}
</style>
<link rel="stylesheet" href="style4.css" media="all" />
</head>
<body>
<header class="clearfix">
<div id="logo">
<img src="logo1.png">
</div>
<div id="company">
<h2 class="name">App</h2>
<div>address</div>
<div>phone</div>
<div>email</div>
<div>web</div>
</div>
</div>
</header>
<main>
<div id="details" class="clearfix">
<div id="client">
<div class="to">Plate:</div>
<div class="address"><?php
require 'conn.php';
$result = $conn->query("SELECT * FROM vehicles WHERE plate=(SELECT plate FROM visits WHERE vid='".$_POST["user_id1"]."')");
$row = mysqli_fetch_array($result);
echo $row['plate'];
?></div>
</div>
....
....
..
.
.
The problem is that $_POST["user_id"] variable isn't recognized as in second file, which is only php. Is there any special technique to pass that variable in third file?
I've tried different combinations and i can't figure out what i'm missing.
The two separate requests to print/print_fumes_card.php make little sense based on the information provided. The initial ajax post passes only user_id1 and does not appear to be attempting to make any change to the data. The second request does not pass the param at all. Just pass the param in the window.open call -
$(document).on('click', '.print_fumes_card', function(){
var user_id1 = $(this).attr("id");
alert(user_id1);
window.open ('print/print_fumes_card.php?user_id1=' + user_id1, '_blank');
});
And then -
<?php
require 'conn.php';
echo $_GET['user_id1'];
?>
The comment about understanding the SQL Injection vulnerabilities and using prepared statements still stands. At the very least you should force the type -
$user_id1 = (int) $_GET['user_id1'];
I'm working on a hangman game using html, css, js and php.
Using php you get a random word from a xampp mysql server in an unordered display.
By using javascript, input boxes are automatically created depending on the length of the word.
After filling all input boxes a submit button appears.
The problem is that before implementing php functionality to get an item from the DB I was testing my app only with js with a given word var word = "Rhodes" . After implementing php and managing to display a randomized word from the DB in my screen and modifying my js code I also got the word ="Rhodes" next to my random word and only input boxes corresponding to "Rhodes" length instead of the new word .
In other words the code I deleted still runs like it was never
modified .
I have my new code below . With js I get the php word to create input boxes . It doesn't work and the old code is displayed .
function hangman(){
var island = document.getElementById("random-island"); //the given word that is supposed to be found
createSpaces(island);
const inputLists = document.querySelectorAll("input");
document.querySelectorAll("input").forEach(el => {
el.addEventListener('input', evt => {
const showButton = [...inputLists].filter(ip => ip.value.trim() !== '').length === inputLists.length;
document.getElementById('submitbtn').style.display = showButton ? 'block' : 'none';
});
});
}
function createSpaces(text){
for(var i=0;i<text.length;i++){
var space = document.createElement("input");
space.setAttribute("class" , "dash");
document.getElementById("hangman-container").appendChild(space);
}
}
.transparent-box {
border:none;
position:absolute;
top:10%;
left:15%;
background-color:black;
height:500px;
width:70%;
opacity: 0.6;
}
.transparent-box p {
color:white;
text-align:center;
}
.transparent-box h1 {
color:white;
position: relative;
text-align:center;
font-size:20px;
top:30px;
}
#hangman-container {
position: relative;
width:auto;
top:30%;
left:0%;
background-color: transparent;
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.dash {
margin:0;
padding:20px;
align-items: flex-start;
width:4%;
border:none;
border-radius: 5%;
background-color: turquoise;
color:red;
font-size:40px;
}
.dash:focus {
opacity:0.8;
}
#submitbtn {
display: none;
position: absolute;
top:200%;
left:80%;
float:right;
}
<body onload = hangman()>
<div class = "transparent-box" id = "t-box">
<p>Play here </p>
<h1 id = "hidden-word">The word is :
<?php
$link = #mysqli_connect('localhost' , 'root' , 'password' ,'dbname');
if(!$link){
echo 'Error connecting to DB';
exit;
}
$query = "SELECT island_name FROM dodecanese ORDER BY RAND() LIMIT 1";
$result = #mysqli_query($link, $query);
if(!$result){
echo 'There is an issue with the DB';
exit;
}
$row = #mysqli_fetch_assoc($result);
echo '<span id = "random-island">'.str_shuffle($row['island_name']). '</span>';
?>
</h1>
<form id = "hangman-container" method="POST">
<button type = "submit" class = "hide" id="submitbtn">Submit</button>
</form>
</div>
</body>
I would appreciate your help with this . Thank you in advance .
I do not fully understand what your actual question is.
But if I understood correctly - you would like PHP to play a role in this game.
(i.e. PHP to connect to the database instead of javascript doing everything itself by having a big list of words in the array, pick it up, doing checks all in client-side).
Then what I would suggest having at least 3 files (not mentioning assets):
Index.html
NewWordGenerator.php
WordChecker.php
Additionally, I would suggest you to spend some time if possible familiarising with ajax. jQuery might give you an easier entry point for ajax.
Suggested workflow:
Index.html file that has a start button, js + ajax code, placeholders, styling etc.
When a visitor would press "start the game" button, it would trigger ajax to make a call to NewWordGenerator.php file which would connect to the database and get any random word from your database, which would be displayed in index.html when ajax is successful, js to "cut" the word into letters and put it to placeholders/form etc.
When a player would click submit button, javascript/jQuery would prevent default form submission, send user input via ajax to WordChecker.php which would be handling checking the word and giving the result that is returned and displayed in index.html.
Hope that makes sense.
A bit of background, I mainly work in .Net/C# and never did any PHP my whole life and my company gave me an existing PHP code and asked me add some feature to it.
The webpage I need to work on is a catering system. The page recalculates the total price when there are changes to the number of pax. This worked fine if every item in the menu is similarly priced.
function RefreshPrice() {
menuid = getQueryString('menuid');
$.ajax({
url: "ajax.php",
type: "POST",
data: {
refreshprice: "refreshprice",
menuid: menuid,
},
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
But now there are items that cost more than others, so I need to recalculate on each item selection. I'm trying to use a hidden field to store the additional price for the item.
<input type="checkbox" class="validate-checkbox" item-name="<?php echo $item["Name"];?>"
name="menuitem[]" value="<?php echo $item["Id"];?>">
<input type="hidden" class="addprice" name="addprice" value="<?php echo $item["AddPrice"];?>">
But how do I get the values of the hidden field of each selected item so I can do something like this.
function RefreshPrice() {
menuid = getQueryString('menuid');
addprice= document.getElementsByClassName("addprice:checked").val(); //OR $(".addprice:checked").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: {
refreshprice: "refreshprice",
menuid: menuid,
addprice: addprice,
},
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
Sorry if this is a duplicate question, but most answer I found were using form submit POST method and got them using $_POST["addprice"], but this is manually constructing the ajax POST.
I think its not a good idea to store values in hidden form fields. because for security reasons user can modify your old values.
my suggestion is, you should send form value to your PHP and make a DB call and compare the values again. if you found the changes then update value otherwise leave it.
As I'm sure you've realized it is a security issue to calculate prices from data that can be altered on the client-side. Also, if the server-side is simply there to add the values, why not handle it directly in the javascript.
either way, the code below should collect data values of the checked items.
<input type="checkbox" class="validate-checkbox priceItems" item-name="<?php echo $item['Name'];?>" name="menuitem[]" value="<?php echo $item['Id'];?>" data-price="<?php echo $item['AddPrice'];?>">
you can add prices as a parameter to the data of the ajax function or do the sum here.
var prices = $('.priceItems:checked').map(function() {
return $(this).data('price');
}).get();
After doing some research and lots of testing I found a way to achieve what you desire so here is an example of it...
I've been testing this example on an app that I am building so the example will not be using your code, but the method is the same, you will just need to adjust it to work with your code...
Okay so first let's create the needed table and populate it with few rows
PHP
// Establish Connection (change the connection details if necessary)
$mysqli = new mysqli ('localhost','root','','test');
// Create table
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS permissions(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL
)");
// Populate table
mysqli_query($mysqli, "INSERT INTO permissions (
name,
description
) VALUES (
'manage_users',
'Can add/edit users'
),
('permission_plus',
'Can manage roles/permissions & access logs'
)");
?>
So, in this example I will be trying to create a new role for my web office and assign the role some of the existing permissions and to achieve that we will need to create a form that will display all of the existing roles from the table that we have just created...
HTML
<!--Make sure to include JQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<div id="addRole">
<form method="POST" id="addroles">
<input type="text" id="rolename" placeholder="Role Name" />
<input type="text" id="role_description" placeholder="Role Description" />
<hr /><span class="title">Include Permissions</span>
<div id="checks">
<?php
$query = mysqli_query($mysqli, "SELECT * FROM permissions");
while($row = $query->fetch_assoc()){
$permid = $row['id'];
$permname = $row['name'];
$permdesc = $row['description'];
echo "<label class='checks' title='$permdesc'>
<input type='checkbox' class='selected' data-id='$permid'/>
$permname</label>";
}
?>
</div>
<input type="submit" value="Add Role" />
</form>
</div>
Now, after we have the form displaying all the rows from the "permissions" table in a form of a checkbox, we can finally come to the most important part of the code, which is storing the selected checkboxes in an array using JavaScript/JQuery and passing them on to the server using AJAX...
JavaScript
$('#addroles').on('submit', function(event){
event.preventDefault();
let rolename = $('#rolename').val();
let roledesc = $('#role_description').val();
let permissions = [];
$('.selected').each(function(){
if($(this).is(":checked")){
permissions.push($(this).data('id'));
}
});
if(rolename != '' && roledesc != ''){
$.ajax({
url: 'addrole.php',
method: 'POST',
data: {
rolename: rolename,
roledesc: roledesc,
permissions: permissions
},
success: function(data){
console.log(data);
}
});
}
});
As you can see, the script here says, after you submit the form, first prevent it from it's default function and assign the values from the form fields to this specific variables, and when it comes to the checkboxes, create an array and then for each checked checkbox - push the value stored in data-id inside the previously created array, then fire AJAX and pass on all the variables to the server and after the server handles the data, please tell us what it said
addrole.php
$mysqli = new mysqli ('localhost','root','','test');
$permissions = $_POST['permissions'];
foreach($permissions as $permission){
echo $permission.' ';
}
The server breaks down the passed array of selected checkboxes using a foreach function and echoes the value stored in the data-id of each selected checkbox and we can see the result of it in our browser's console.
Here is some CSS for the sake of the appearance of this example
CSS
#addRole{
background-color: rgb(241, 241, 241);
position: relative;
width:30%;
padding:20px;
}
#addRole input[type='text']{
width:80%;
height:40px;
margin:5px 5px 5px 0px;
position: relative;
left:50%;
transform: translate(-50%);
text-align: center;
outline:none;
}#addRole input[type='submit']{
width:80%;
height:40px;
margin:5px 5px 5px 0px;
position: relative;
left:50%;
transform: translate(-50%);
text-align: center;
outline:none;
}
#addRole form hr{
width:30%;
margin-bottom: 20px;
margin-top: 20px;
}
.checks{
display: inline-block;
padding:20px;
text-indent: -20px;
background-color: rgb(252, 252, 252);
border:1px solid rgb(238, 238, 238);
margin: auto;
}
#checks{
position: relative;
left:50%;
transform: translate(-50%);
margin:10px;
display: flex-box;
text-align: center;
}
#addRole input[type='checkbox']{
width:20px;
height:20px;
margin:0px 0px 0px 20px;
outline:none;
text-align: center;
}
.title{
position:relative;
left:50%;
transform: translate(-50%);
text-align: center;
display: inline-block;
font-size: 20px;
margin:auto;
margin-bottom: 10px;
}
I am trying to make code that lets me add checkmarks to clicked images from my database. I am able to get the images to display, however I am unable to select the image/get the check to appear.
index.php
<?php
$result = mysql_query("select * from db");
$count = 0;
while ($row = mysql_fetch_array($result)) {
$count++;
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['img']) . '" width="290" height="290" class = box>';
}
?>
click.js
$(document.ready(function(){
$('.box').live("click", function() {
if($(this).find('.check_image').length == 0){
$(this).append("<div class='check_image'><img src='check.png' /></div>");
}else{
$(this).find('.check_image').remove();
}
});
Ok so I would suggest getting CSS to do display the tick. It will mean wrapping your echoed img tab in a div (you can't use the pseudo selector :after directly on an img tag alas. I have used a font library (font-awesome) this is a great way of getting icons like ticks and trashcans etc into your pages. They scale and can be coloured.
as has been mentioned in other posts you are using some depreciated calls in both your PHP and jQuery. Have a play with this:
$('.clickable').on('click',function(e){
$(this).toggleClass('clicked');
})
.clickable.clicked:after{
font-family: FontAwesome;
content: "\f00c";
color:lime;
position:absolute;
top:2px;
right:2px;
font-size:40px;
text-shadow: -2px 3px 2px rgba(150, 150, 150, 0.8);
}
.clickable{
cursor:pointer;
position:relative;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickable" style="width:320px;height:240px;">
<img src="http://www.richardhulbert.com/wp-content/uploads/2011/04/New-Forest-11.jpg" alt="nice van bros!" />
</div>