Passing values from a php generated table to modal - javascript

I got a table generated in PHP:
<tbody>
<?php
$results = DB::select()->from('users')->execute();
foreach ($results as $user) {
echo "<tr id='".$user['id']."'>
<input type=\"hidden\" id='userNameHidden' value='".$user['username']."'>
<input type=\"hidden\" id='userEmailHidden' value='".$user['email']."'>
<td class='username'>".$user['username']."</td><td class='email'>".$user['email']."</td><td class='lastlogin'>".date('d/m/Y',$user['last_login'])."</td><td class='logins'>".$user['logins']."</td><td><a class='editThis'><i class=\"small material-icons\">mode_edit</i></a> delete</i> </td></tr>";
}
?>
My question is, how to make the edit/delete buttons work on a modal that is opened on the same site? I just want to pass values from <td> to <input type="text"> on the modal.

You can send it with GET or POST method to another php file and than work with them there. If you want to work on the same page you can get it via JavaScript:
var value = document.getElementById ( "userNameHidden" ).innerText;
After that:
document.getElementById ( "inputid" ).value = value;
If you would like to create a login system definately use POST or GET (not recommended) to pass the values.
If you want it to happen with a button click. You can make a funcion and a button to go with it:
<button onclick="delete()">Delete</button>
And the js:
function delete(){
var value = document.getElementById ( "userNameHidden" ).innerText;
document.getElementById ( "inputid" ).value = value;
}

Related

How to get value of buttons in a PHP foreach loop in Javascript

I'm working on a very simple social media webapp to practice PHP & Ajax. Users get some friend suggestions, and when they send a request I want the recipient to get a little notification using Ajax.
The request button is in a foreach loop, like so:
<?php foreach ($suggestions as $suggestion) : ?>
[...]
<form action="" method="post" id="formRequest">
<input type="hidden" name="userID" class="userID" value="<?php echo $userID ?>">
<input type="hidden" name="buddyID" class="buddyID" value="<?php echo $suggestion['userID'] ?>">
<input type="submit" value="Add as friend" name="request" class="request">
</form>
To test if Ajax gets the right buddyID value when I click 'Add' a specific user, I have tried this:
let request = document.querySelector(".request");
request.addEventListener("click", function() {
let buddyID = document.querySelector(".buddyID").value;
console.log(buddyID);
})
but this only logs the first suggested buddy's ID (so only when I click the first button); the console stays empty when I add the 2nd or 3rd suggested buddy.
My guess is I'll have to use a for loop, but when I tried to add one it wouldn't print anything at all.
In order to assign the click event listener to all the buttons rather than just to one you could try something like this using querySelectorAll to find the nodelist through which you iterate.
Array.from( document.querySelectorAll( 'input[type="submit"].request' ) ).forEach( bttn=>{
bttn.addEventListener('click',(e)=>{
e.preventDefault();
let buddyID=e.target.parentNode.querySelector('.buddyID').value;
let userID=e.target.parentNode.querySelector('.userID').value;
console.info( buddyID, userID );
});
});
You could simplify things further by removing the forms ( which don't really do anything here anyway if you use AJAX ) and simply have a singular button per record / suggestion that has the necessary information assigned to it in the form of dataset attributes.
<?php
foreach( $suggestions as $suggestion ) {
?>
<input class="request" type='button' data-buddyID="<?php echo $suggestion['userID'];?>" data-userID="<?php echo $userID;?>" value="Add as friend" />
<?php
}
?>
Array.from( document.querySelectorAll( 'input[type="button"].request' ) ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
e.preventDefault();
let buddyID=this.dataset.buddyID;
let userID=this.dataset.userID;
console.info( buddyID, userID );
});
});

How to get either select .val() or div .text() from dynamically created elements with same id?

Depending on the user type, my page dynamically creates either a select element (for admins to change) or a div with text (for regular users) using the same id.
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher' >teacher</option>";
echo "</select></td></tr>";
}
else echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
When the page submits, I need either the .val() from the select element or the .text() from the div element.
I can't use .val() on the div element and I can't use .text() on the select element.
Is there a way in jQuery / javascript to get one or the other, depending on which element type was created?
make the else statement as so (use input[type=hidden], to use the .val())
else echo
"<tr>
<td>Type:</td>
<td>
<!-- div to show the value -->
<div>$user_type</div>
<!-- hidden input type to get the value via jQuery .val() -->
<input type='hidden' id='type' value='$user_type'>
</td>
</tr>";
Oh by the way, you can use PHP variables inside strings that are defined with double quotes echo "$someVar";
Since you are printing out from PHP the HTML out put, by the same time you can print a Javascript variable who has what method use to get the value/text. Then, use the variable in your Javascript to perform one query or other.
Something like :
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher'>teacher</option>";
echo "</select></td></tr>";
echo "<script> var method = 'val'</script>";
}
else
{
echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
echo "<script> var method = 'text'</script>";
}
You can check it with the following simple code in javascript:
if(document.getElementById("type").tagName == "SELECT") {
//Your code for admin
}
else
{
//Your code if it is not admin
}
You can have the text or the value with a simple and elegant ternary condition :
var result = $("#type").val() !== undefined ? $("#type").val() : $("#type").text();

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Pass checkbox value to Edit (using href)

I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']

getting value of second input located inside the form. javascript jquery

I have this html form
echo "<form name='delete_article_form".$row['id']."' action='sources/public/article_processor.php' method='POST' >";
echo "<input name='processor_switcher' id='processor_switcher' type='hidden' value='delete_article'><input name='article_id' id='article_id' type='hidden' value='".$row['id']."'><a class='delete_button' href='#'>".$s_delete[$lid]."</a>";
echo "</form>";
Now here is jquery code
$('.delete_button').live('click',function(){
article_id = ???????
alert(article_id);
});
What should I do to get the value from input named "article_id"?
Problem is that I have several such forms on my page so I must use THIS statement.
input=$('input',this).val(); will not help cause there are 2 inputs.
Any Ideas?
Try
var article_id = $(this).closest('form').find('input[name="article_id"]').val();
If you want the 'second' input, then you can do this
var article_id = $(this).closest('form').find('input').eq(1).val();
Use eq(1) to get the second element from the matched set of elements.
article_id = $('input:eq(1)',$(this).closest('form')).val();
Since you have an id to the input fields you can also use. The ids of elements on the page should be unique.
input = $("#article_id").val();

Categories

Resources