creating a list/array of items from select - javascript

Background: I am using HTML/PHP/MySQL/ and Javascript if needed
What I have is a list of approximately 1000 people - I want to let the user select people, and then use the selected people to add them to a database.
I was thinking that each row of the table would have a unique link, and the link would either add that person to an array - or to some kind of list - and then at the end I can take that list and input it into the database..
I really want to have it that when somebody clicks a person's name - it automatically gets added to a list on lets say the left hand side - then once they are done, they can submit the list.
let me know if clarification is needed.
Thanks for your help!

I would go with:
Create page with space for smaller list on the left and list of people on the right.
Display people, with pagination, in table using something like this:
<table id="people">
<tr>
<td id="<?php echo $person['id']; ?>"><?php echo $person['name']; ?></td>
</tr>
</table>
When someone clicks on tr javascript code is executed to send post request with id the person. PHP file responsible for handling this stores the id in the $_SESSION['selectedPeople'] array or removes it from there if it is present. Also, when you click on td, .selected class is toggled and list of selected people on the left side is updated(for example, via getting JSON from PHP file and processing it to display in the table).
you can press submit at any time. It would:
a) take you to the other page and submit the list(you have $_SESSION['selectedPeople'] variable)
b) send an ajax call to page which will process $_SESSION['selectedPeople']
Some code:
selectHandler.php:
<?php
if($_POST && isset($_POST['id'])) {
$id = (int)$_POST['id'];
$action = '';
session_start();
if(!isset($_SESSION['selectedPeople'])) {
$_SESSION['selectedPeople'] = array($id);
$action = 'added';
} else {
if(in_array($id, $_SESSION['selectedPeople'])) {
$_SESSION['selectedPeople'] = array_diff($my_array, array($id));
$action = 'removed';
} else {
$_SESSION['selectedPeople'][] = $id;
$action = 'added';
}
}
echo json_encode(array('action' => $action));
}
?>
Javascript(+JQuery):
$(function () {
$('#people tr').click(function () {
var id = $(this).children('td[id]').attr('id');
$.post("selectHandler.php", { id: id })
.done(function( data ) {
if(data.action == "added") {
$(this).addClass('selected');
} else if(data.action == "removed") {
$(this).removeClass('selected');
} else {
alert('Some kind of error.');
}
}, "json");
refreshSelectedList();
});
});
I hope you get the idea.

Related

On clicking a button how to run php script

Im a beginner in PHP. I want to add the Functionality to like button. Whenever a user clicks like button then the insert query is to be run to insert values in db. There are several images on home page, the corresponding productimage info(productid) must be inserted in product_likes db.`
<?php
$user_name=$_SESSION['user_name'];
$query="SELECT * FROM product_info";
$result= mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="w3-container"><br>
<img src="<?php echo "img/product_img/".$row['productimage'].""; ?>">
<p><b>Product Name: </b><?php echo"".$row["productname"].""?><br>
</p>
<form id="like" method="post" action="home1.php">
<button type="submit" name="like"><i class="fa fa-heart"></i>  Like</button>
<?php
if(isset($_POST['like'])){
$result=mysqli_query($con,"INSERT INTO product_likes VALUES ('','".$row['productid']."','".$row1['sellerid']."','".$buyerid."')");
}
?>
</form>
</div>
<?php } ?>`
But whenever I run this the same productid, sellerid and buyerid corresponding to first image are inserted in database and only the first image is displayed. Is there a way to correct this issue?
First thing that you need to understand is, PHP is server side language, gets executed before the client, and JavaScript is client side language, gets executed after the server side has finished processing and there's no going back to the server.
When you want to do something like speaking to a server based on user's behaviour, you need to have an end-point configured and fire an AJAX call to the server. Simple example using jQuery to like a post would be:
$(function() {
$("a").click(function(e) {
e.preventDefault();
$this = $(this);
if ($(this).text().trim() == "Like") {
$.post("/posts/like", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Unlike");
});
$this.text("Unlike");
} else {
if ($(this).text().trim() == "Unlike") {
$.post("/posts/unlike", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Like");
});
$this.text("Like");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Like
The above example kinda "works", because of the fall-back, but pretty much this is the concept. The whole PHP code that makes the "Like" or "Unlike" should be given separately and using jQuery's AJAX function, you need to fire it off.
Both the above URLs: /posts/unlike and /posts/like take in a data parameter PostID and based on that make the necessary changes in the database.

How to get div content that was echoed by PHP

I need to get a value inside a div content. After a button click and doing stuff on the server side, my PHP function does:
echo "0";
or
echo "1";
depending on what my function does. So let's say if it's 0, the AJAX response will be $("div#divResult").html(data); where I put the 0 in the div divResult.
What I am trying to do now is I want to execute a js function to read whether it's 0 or 1 in divResult.
This is how I execute it:
<div id="divResult"><script>getDivResult();</script></div>
And my js function:
function getDivResult()
{
var result = $("div#divResult").text();
if(result === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(result === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
}
Somehow the getDivResult function is not executing. The 0 and 1 does display on in the div though. Any help on this? I've tried .html too by the way.
EDIT:
Here's the AJAX that I use for the button click and return the response from PHP which is either 1 or 0:
$.post(page, {
name : name,
badge_number : badge_number,
category : category,
priviledge : priviledge,
action : "insert"
}, function(data) {
$("div#divResult").html(data);
});
2nd EDIT:
function insertRow($name, $badge_number, $priviledge, $category)
{
$table_info = "TBL_USER_LOGIN";
$query_string = "select badge_number from $table_info where badge_number = $badge_number";
$result = #mysql_query($query_string) or die (mysql_error());
$checkBadge = mysql_num_rows($result);
if($checkBadge>0)
{
//echo "Badge Number $badge_number already exists. Please check again.";
echo "0";
}
else
{
$query_string = "insert into $table_info(name, badge_number, priviledge, category) values('$name', '$badge_number', '$priviledge', '$category')";
$result = #mysql_query($query_string) or die (mysql_error());
//echo "Your details have been entered! Please click on 'View Users' to display all users.";
echo "1";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="delete")
{
$id = rtrim($_REQUEST['id']);
$order = $_REQUEST['order'];
echo deleteRow($id);
echo selectAll($order);
}
elseif($action=="insert")
{
$name = $_REQUEST['name'];
$badge_number = $_REQUEST['badge_number'];
$priviledge = $_REQUEST['priviledge'];
$category = $_REQUEST['category'];
echo insertRow($name, $badge_number, $priviledge, $category);
}
elseif($action=="update")
{
$order = $_REQUEST['order'];
echo selectAll($order);
}
?>
You shouldn't need to append the return data to the page at all. Why don't you run your function immediately after the AJAX request completes, like so:
$.ajax({
success: function(data) {
if(data === "0") {
alert("Badge Number already exists, please check again.");
}
else if(data === "1") {
alert("Your details have been entered!")
ADD_USER_POPUP.close();
}
}
});
place getDivResult() to onclick in which button you click like
< button onclick="getDivResult()">Click me< /button>"
i think it will be work with you.
enclose the echo with a div then trying getting the value by the id.
or
try echoing via json enconde
json_encode
then fetch the value by using AJAX
i think, this script <script>getDivResult();</script> was replaced the content of #divResult by ajax code $("div#divResult").html(data);. Instead of that, place the script inside head section rather than inside #divResult to execute that.
Where is your ajax? How do you do it?
It looks like you're using jQuery. Try reading the documentation
https://api.jquery.com/jquery.get/
You can try something like this:
$.get( "ajax/test.html", function( data ) {
if(data === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(data === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
});
data should be your 0 or 1
When you do .html(data) all the existing elements wipedoff and replaced by new content:
$("div#divResult").html(data);
I guess you should do this:
$("div#divResult").html(data);
getDivResult(); // call after it. and put the function globally.
Run your function
getDivResult();
after
$("div#divResult").html(data);
in ajax

Will this huge javascript array loaded from a database crash my website?

So on this website I'm making (who knows if i'll actually finish it lol) when someone opens up the new user page, php echos into a javascript script all the usernames from the database to create an array.
<script type="text/javascript">
var allUsers = ['!' <?php
$result = mysql_query("SELECT username FROM users ") or die("error " .mysql_error());
$usersArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$usersArray[] = $row['username'] or die("error ". mysql_error());
}
foreach ($usersArray as $name) {
echo ',' . json_encode($name );
}
?> , ];
the point of this is to have a live checker so if you type in a username that already exists, red text shows up next to the username input. But let's say I get 1,000,000 users (completely theoretical). Fortunately, the array only gets created at the beginning of the web page load. But will the function that checks if the username already exists in the huge array and gets called everytime someone changes the text in the username input put too much stress on the script and crash the website? If so, is there a better way to do what I'm describing?
Here's the rest of the code
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function onUserChange() { //gets called onkeypress, onpaste, and oninput
if(contains(allUsers, str)) {
div.innerHTML = "Username already exists";
div.style.color = "red";
userValid = false;
}
}
</script>
Something along these lines. ( with jQuery and PDO ) - note - code is not tested.
var keyTimer, request;
$('namefield').blur(function(){
onUserChange();
});
$('namefield').keyup(function(){
onUserChange();
});
function onUserChange() { //gets called onkeypress, onblur
keyTimer = setTimeout(function(){
if(request && request.readystate != 4){
//cancel a previous request if a new request is made.
request.abort();
}
request = $.post(
'http://yoursite.com/location/of/username/script.php', //post data to server
{username : $('namefield').val()},
function(data){
if(data == 0 ) { //might be a string here
alert( 'the name is ok to use.' );
}else{
alert( 'someone has this name already.' );
}
}
);
}, 500); //overwrite previous timeout if user hits key within 500 milliseconds
}
Then in the backend
$sql = 'SELECT id FROM users WHERE username = :username';
//insert from post username but we are good programers and are using PDO to prevent sql injection.
//search for the username in the db, count the number of users or rows should be 1 someone has it 0 no one has it assuming its unique.
$stmt = $Pdo->prepare($sql);
$stmt->execute(array(':username', $_POST['username']));
echo $stmt->rowCount();
exit();
etc.....
Do not do it. My counsel is to use ajax to load the php file that will make a query asking only for the user that was typed in the input and retunr only a boolean value(exists=true / notexists=false)
Code example:
HTML(yourFile.html):
<script>
jQuery(document).ready(function(){
//When the value inside the input changes fire this ajax querying the php file:
jQuery("#inputUser").change(function(){
var input = jQuery(this);
jQuery.ajax({
type:"post",
url:"path/to/file.php",
data:input.val(),
success: function(data){
//if php returns true, adds a red error message
if(data == "1"){
input.after('<small style="color:#ff0000;">This username already exists</small>');
//if php returns false, adds a green success message
} else if(data == "0"){
input.after('<small style="color:#00ff00;">You can use this username</small>');
}
}
});
});
});
</script>
<input id="inputUser" type="text" name="username" value="">
PHP(path/to/file.php):
<?php
$username = $_REQUEST['username']; // The value from the input
$res = mysqli_query("SELECT id FROM users WHERE username='".$username."'"); // asking only for the username inserted
$resArr = mysqli_fetch_array($res);
//verify if the result array from mysql query is empty.(if yes, returns false, else, returns true)
if(empty($resArr)){
echo false;
} else{
echo true;
}
?>
As I can see you need to load the PHP code when your website is loading.
First, I recommend you to separate the code. The fact that you can mix Javascript with PHP doesn't mean it is the best practice.
Second, yes, it's not efficient your code since you make Javascript load the result so you can search into it next. What I suggest you is making the search in the server side, not in client side, because as you say, if you have 100 elements maybe the best is to load all the content and execute the function, but if you have 1,000,000 elements maybe the best is to leave the server to compute so it can make the query with SQL.
Third, you can do all this using Ajax, using Javascript or using a framework like jQuery so you don't have to worry about the implementation of Ajax, but you only worry about your main tasks.

Changing PHP function to Javascript/AJAX validation

I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.

Ignoring links, checkboxes.. in an editable html field using jquery

Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out

Categories