html/PHP form not submitting after being generated with AJAX - javascript

I have a table full of forms that work normally, but after being filtered by a drop down using AJAX, the submit buttons aren't working anymore.
This is the table generated by AJAX
<table class="striped" style='padding-top:20px;'>
<tr class="header" style='border: solid 2px black; background-color: #FFF500; text-align:center; color: black;'>
//All the tds
</tr>
<?php
while ($row = mysqli_fetch_array($query)) {
echo "<tr ><form action=someURL.php method=post>";
//all the data generated inside
echo "<td><input type='submit' name='submit' value=Submit></td>";
echo "</form></tr>";
}
?>
</table>
This is the dropdown that calls makes the AJAX call the form
<select id="selectStuff" name="selectStuff" class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" style="font-size: 15px; background-color: white; width: auto;">
<option value="">Select Something</option>
<?php
$query="SELECT iddivisiones,nombre FROM divisiones";
$db=mysqli_query($con,$query);
while($d=mysqli_fetch_assoc($db)){
echo "<option value='".$d['iddivisiones']."'>".$d['nombre']."</option>";
}
?>
</select>
and here's the script with the AJAX
<script>
$(document).ready(function(){
$('#selectStuff').on('change',function(){
var selectedId=$(this).val();
if(selectedId){
$.ajax({
type:'POST',
url:'categoria-resultados.php',
data:'seleccion='+selectedId,
success:function(html){
$('#tables').html(html);
}
});
}else{
$('#tables').html('<option value="">failed</option>')
}}); });
And the div where the forms table is supposed to appear
<div class="tables" id="tables"> </div>

Related

My JavaScript pop up modal only works on the first row

First question: I have a dynamic table, with edit icon on every row, when pressing the icon a popup modal should show up. But the popup modal only work on the first row. I tried to determine the problem and I think it’s because of the id "open5", that it’s duplicated and only work for one row which is the first row. How can I make it appear on every row?
Second question: how can I use the book id to determine which book going to be updated, when the user press the button on the update modal?
trackingPage.php
<!-- dynamic table -->
<div class="container">
<table class="_table">
<thead>
<tr>
<th>الغلاف</th>
<th>العنوان</th>
<th>المؤلف</th>
<th>تاريخ البدء</th>
<th>تاريخ الإنتهاء</th>
<th>التقدم</th>
<th width="50px">
</th>
</tr>
</thead>
<tbody id="table_body">
<?php
$query = "SELECT * FROM `tracking` WHERE `username_tracking`='$_SESSION[username]'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><img style='width:80px; height: 85px; border-radius: 10px; margin: 0.1px;' src="upload/<?php echo $row['cover'] ?>"></td>
<td><?php echo $row["book_name"] ?></td>
<td><?php echo $row["author_name"] ?></td>
<td><?php echo $row["start_date"] ?></td>
<td><?php echo $row["end_date"] ?></td>
<td>
<div class='progress-container'><progress value='<?php echo $row["current_page"] ?>' max='<?php echo $row["page_number"] ?>'></progress></div>
</td>
<td>
<div class='action_container'>
<a href='delete_book.php?book_id=" <?php echo $row["book_id"] ?> "' class='danger' onclick='remove_tr(this)'><i class='fa fa-close'></i></a>
<a class='success' id='open5'>
<i class='fa fa-plus'></i>
</a>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div class="modal-container-tracking" id="modal_container5">
<div class="modal-tracking">
<form class="book-form" method="post" action="trackingPage.php" enctype="multipart/form-data">
<!-- Modal content -->
<div class="closeIcon-tracking" id="close5">
<span class="close-tracking">×</span>
</div>
<div class="modalContent-tracking">
<h3>تحديثات الكتاب</h3>
<input type="number" name="current_page" placeholder="عدد الصفحات المقروءة" class="pages" min='1' required />
<input name="end_date" placeholder='تاريخ الانتهاء' type="date" class="start-date" required />
<textarea class="review" name="review" placeholder="مراجعة الكتاب"></textarea>
<button href="" name="update_book" class="bn60" style="text-decoration: none;">حدِّث الكتاب</button>
</div>
</form>
</div>
</div>
<script>
//Popup page
const open5 = document.getElementById('open5');
const modal_container5 = document.getElementById('modal_container5');
const close5 = document.getElementById('close5');
open5.addEventListener('click', () => {
modal_container5.classList.add('show');
});
close5.addEventListener('click', () => {
modal_container5.classList.remove('show');
});
//end of Popup page
</script>
This is my DB:
Users table
Tracking table
Your JavaScript code is looking for an element with the ID open5, HTML id's should be unique, but your PHP code renders an element with the same ID for every row, ergo the JS code is satisfied when it finds the first element with ID open5 and therefore all subsequent ones do not get event listeners attached. You have to switch to a class and then attach a listener to each of those links, e.g. something like this:
document.querySelectorAll('tr .success').forEach(function(el, i, nodeList) {
el.addEventListener('click', () => {
modal_container5.classList.add('show');
});
}

Using select option embeded in a table to dynamically change a user role to different roles via JQuery and AJAX

Im trying to dynamically allow the user to change a user role by using a select tag within a table which, when change triggers an event, record the changes in JQuery and send the changes to PHP via AJAX. From the image attached, the only select tag which fires an event is the one in the first row of the table shown. Any changes made to other rows does not fired an event as shown by one of the images with the console.log information. I am trying to allow whoever has the rights to change a specific user role by selecting the adajacent select option within the same table row which is send via AJAX to change the field in the database. I have posted this question before however Wesley Smith recommended I do a new post. Anyone please feel free to comment.
<?php
require_once('../../private/initialize.php');
require_login();
$admins = find_all_admins();
?>
<?php
if(isset($_SESSION['message']) )
{
echo "<div> </div><h5 style=\"color: #08ff00\">". $_SESSION['message'] ."</h5> </div>";
}
unset($_SESSION['message']);
//if(isset($SESSION['image_msg']))
//{
// echo "<div> </div><h5 style=\\" . $_SESSION['image_msg'] . "</#ffffff> </div>";
//}
?>
<form action="" method='post'>
<table class="table table-bordered table-hover">
<!-- <div id="bulkOptionContainer" class="col-xs-4">-->
<!---->
<!-- <select class="form-control" name="bulk_options" id="">-->
<!-- <option value="">Select Options</option>-->
<!-- <option value="published">Publish</option>-->
<!-- <option value="draft">Draft</option>-->
<!-- <option value="delete">Delete</option>-->
<!-- <option value="clone">Clone</option>-->
<!-- </select>-->
<!---->
<!-- </div>-->
<div class="col-xs-4" id="addnew" >
<!-- <input type="submit" name="submit" class="btn btn-success" value="Apply">-->
<a class="btn btn-primary" href="staff.php?source=add_staff">Add New</a>
</div>
<thead>
<tr>
<!-- <th><input id="selectAllBoxes" type="checkbox"></th>-->
<th>Image</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Role</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while ($all_admins = mysqli_fetch_assoc($admins)) { ?>
<tr>
<td><img src="<?php echo url_for('../images/staff/'.$all_admins['image'])?>" onerror="this.src='<?php echo url_for('../images/staff/profile.jpg') ?>'" style="border:1px solid #ddd;border-radius:2px; box-shadow: #4a5f63; height: 70px;width: 70px"></td>
<td><?php echo h($all_admins['first_name']) ?></td>
<td><?php echo h($all_admins['last_name']) ?></td>
<td><a class='btn btn-info' href="staff.php?source=show_staff&staff_id=<?php echo h($all_admins['id']) ?>"> <?php echo h($all_admins['email']) ?> </a></td>
<td>
<?php
$role = $all_admins['role'];
switch ($role){
case 'DE':
echo "Data Entry";
break;
case 'GU':
echo "General User";
break;
default:
echo "Administrator";
break;
}
?>
<span>
<select class="urole" name="role[]">
<option value="Admin" <?php echo ($role == 'Admin')?'selected':'' ?> >Admin</option>
<option value="DE" <?php echo ($role == 'DE')?'selected':'' ?> >Data Entry</option>
<option value="GU" <?php echo ($role == 'GU')?'selected':'' ?> >General User</option>
</select>
</span>
</td>
<td><a class='btn btn-info' href="staff.php?source=edit_staff&staff_id=<?php echo h($all_admins['id']) ?>">Edit</a></td>
<form method="post">
<input type="hidden" name="post_id" value="<?php //echo $post_id ?>">
<?php
echo '<td><input class="btn btn-danger" type="submit" name="delete" value="Delete"></td>';
?>
</form>
</tr>
<!---->
<!-- <td><input class='checkBoxes' type='checkbox' name='checkBoxArray[]' value='-->
<?php } //echo $post_id; ?><!--'></td>-->
<?php
mysqli_free_result($admins);
// echo "<td><a rel='$post_id' href='javascript:void(0)' class='delete_link'>Delete</a></td>";
// echo "<td><a onClick=\"javascript: return confirm('Are you sure you want to delete'); \" href='posts.php?delete={$post_id}'>Delete</a></td>";
// echo "<td><a href='posts.php?reset={$post_id}'>{$post_views_count}</a></td>";
// echo "</tr>";
//}
?>
</tbody>
</table>
</form>
<?php
//if (isset($_POST['delete'])) {
//
// $the_post_id = escape($_POST['post_id']);
//
// $query = "DELETE FROM posts WHERE post_id = {$the_post_id} ";
// $delete_query = mysqli_query($connection, $query);
// header("Location: /cms/admin/posts.php");
//
//
//}
//
//
//if (isset($_GET['reset'])) {
//
// $the_post_id = escape($_GET['reset']);
//
// $query = "UPDATE posts SET post_views_count = 0 WHERE post_id = $the_post_id ";
// $reset_query = mysqli_query($connection, $query);
// header("Location: posts.php");
//
//
//}
?>
<script>
$(document).ready(function ()
{
// $(".delete_link").on('click', function () {
//
//
// var id = $(this).attr("rel");
//
// var delete_url = "posts.php?delete=" + id + " ";
//
//
// $(".modal_delete_link").attr("href", delete_url);
//
//
// $("#myModal").modal('show');
//});
$('.urole').on('change',function (e){
e.preventDefault();
var val = $(".urole option:selected").val();
console.log(val);
console.log(e);
// $("#urole").on('click', function(){
// v
// });
//displayData(val);
});
$("#urole").ready(function (){
var val = $("#urole option:selected").val();
console.log(val);
//displayData(val);
});
});
function displayData(query){
$.ajax({
url:"enrolled_learners/enrol_learner_provider.php",
method:"post",
data:{query:query},
success:function (data)
{
//console.log(data);
$('#q-provider').html(data);
}
});
}
<?php
//if (isset($_SESSION['message'])) {
//
// unset($_SESSION['message']);
//
// }
?>
</script>
User Interface and Console log[enter image description here][1]
[User Interface][1]
Your selector selects all with the class urole, you just want to select the one that changed, since you're in the change handler for that element you can access it via the this keyword.
$('.urole').on('change',function (e){
e.preventDefault();
var val = this.value;
console.log(val);
console.log(e);
displayData(val);
});

Dropdown select , update user account activate/deactivate

I'm new in php how can I make this work
delete.php
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("UPDATE tbluser set status=1 WHERE id=:id");
$stmt->execute(array(':id'=>$id));
}
?>
I want to add an active/inactive dropdown choice in my edit form page but I dont know how to make it work I dont know how to call the delete.php so that when i choose inactive and submit the form it will not show on my datatable
edit_form.php
<?php
include_once 'dbconfig.php';
if($_GET['edit_id'])
{
$id = $_GET['edit_id'];
$stmt=$db_con->prepare("SELECT * FROM tbluser WHERE id=:id");
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<div id="dis">
</div>
<form method='post' id='emp-UpdateForm' action='#'>
<table class='table table-bordered'>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>' />
<tr>
<td>Status</td>
<td><select name=stats>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-update" id="btn-update">
<span class="glyphicon glyphicon-plus"></span> Save Updates
</button>
</td>
</tr>
</table>
everything is working it's just an additional functionality in the edit form page
Get the stats like $status= $_POST['stats']; in delete.php
change you $_GET['edit_id'] to $_GET['id']
modify you updated to set the status
$id = $_POST['id'];
$status = $_POST['stats']
$stmt=$db_con->prepare("UPDATE tbluser set status=:status WHERE id=:id");
$stmt->execute(array(':status'=>$status,':id'=>$id));
If you want to call the delete.php, you can use ajax.
<script>
$.ajax({
url:'delete.php',
type:'post',
data: $('form').serialize()
});
</script>
You can get values on the delete.php, with the help of $_POST or $_REQUEST.
And if the delete.php code is right, then on submit of the edit_page.php your datatable can get affected.

Jquery- Unable to get alert after changeing the select option

I am trying to get alert on change of select box option.
Here, i added a css class name on each selectbox while iterating it in the loop, and finally i called the jquery function with class selector.
But i do not know why its not showing alert on change of selectbox dropdown. Please help me to solve this problem
<table style="border:1px solid red;" width="650px">
<tr style="border:1px solid red;">
<td">Status</td>
</tr>
<?php
$qry = "select *from tracker group by orderno";
$res = mysql_query($qry) or die(mysql_error());
while($data = mysql_fetch_array($res))
{
?>
<tr style="border:1px solid red;">
<td ><label onclick="show(this.id)" id=<?php echo $data['orderno'];?> > <?php echo $data[1]; ?></label></font></td>
<td ><?php echo $data['customername']; ?></td>
<td align="center" style="border:1px solid red;"><?php echo $data['noofbooks']; ?></td>
<td ><?php echo $data['address']; ?></td>
<td ><?php echo $data['mobileno']; ?></td>
<td align="center" style="border:1px solid red;">
<select name="status" class="selectboxid">
<?php
if($data['status'] == "despatch")
{
echo '<option name="despatched" selected="selected" value="despatched"> Despatched </option>';
}
else
{
echo '<option name="despatched" value="despatched"> Despatched </option>';
}
if($data['status'] == "Pending")
{
echo '<option name="pending" selected="selected" value="pending"> pending </option>';
}
else{
echo '<option name="pending" value="pending"> pending </option>';
}
if($data['status'] == "deliver")
{
echo '<option name="despatched" selected="selected" value="despatched"> Despatched </option>';
}
else
{
echo '<option name="despatched" value="despatched"> Despatched </option>';
}
if($data['status'] == "partial")
{
echo '<option name="partial" selected="selected" value="partial"> Partial </option>';
}
else
{
echo '<option name="partial" value="partial"> Partial </option>';
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
And my jquery code is;
<script>
$(".selectboxid").change(function() {
alert("hi");
});
</script>
Maybe you bind event too soon (before DOM is loaded). Just put jQuery function in jQuery(function(){ }) like code below.
for optional you should use on instead of change, its a recommend style.
jQuery(function(){
$(".selectboxid").on('change', function() {
alert("hi");
});
});
use this, dont need $(document).ready...
<script>
$(document).on("change",".selectboxid",function(){
alert("hi");
});
</script>

How to get array through selected check boxes in jQuery or JavaScript?

I want to get array of user selected check boxes, for example if user select the product1 and in product1 the email is a#acom like that, if user select many check boxes I want all email data in the array which he select against product. The data will get behalf of id, I am stuck at here, working to resolve that issue for 2 days but didn't get success:
<?php v_start($this);?>
<style>
.highlight{ font-wieght:bold; color:#F00;}
.amounts{}
.tick{ float:left; margin-top:-5px;}
.highlight .amount{ display : inline;}
.tick img{ display:none; width : 25px; height : 25px; margin-right: 10px; float : left;}
.highlight .tick img{ display : block;}
</style>
<script>
jQuery(document).ready(function (){
jQuery('.amounts').click(function (){
var pname = jQuery(this).attr('product_name');
if(!jQuery(this).hasClass('highlight')){
jQuery('.amount-'+pname).removeClass('highlight');
jQuery(this).addClass('highlight');
}
else {
jQuery(this).removeClass('highlight');
}
});
});
</script>
<h1><?php echo __l('Step 1 ')?>-> <span style="color:red"><?php echo __l('Step 2')?></span></h1>
<?php echo $this->FormManager->create('User',array_merge($form_options,array('default'=>true)));?>
<table>
<thead>
<tr cellpadding="0" cellspacing="0" width="100%" >
<?php foreach($name as $product) { foreach ($product as $key) {
for($i=0;$i<sizeof($key['ProductPlan']);$i++) {
?>
<th>
<?php echo $key['Product']['name']?>
<?php echo $this->FormManager->input($key['Product']['name'],array('type'=>'hidden','id'=>$key['Product']['name'],'class'=>'hid'))?>
</th>
<?php }}?>
</tr>
</thead>
<tbody>
<tr>
<?php
foreach($name as $product) {
$c = 0;
?>
<?php
foreach ($product as $key) {
$c++;
?>
<td>
<? for($i=0;$i<sizeof($key['ProductPlan']);$i++) { ?>
<div
class = 'packages'
id = "<?php echo $key['Product']['name'],$key['ProductPlan'][$i]['product_plan_id']?>"
onclick = "document.getElementById('<?php echo $key['Product']['name']?>').value='<?php echo $key['ProductPlan'][$i]['product_plan_id']?>';"
>
<div product_name='<?php echo $key['Product']['slug']?>' class='amounts amount-<?php echo $key['Product']['slug']?>'>
<div class='tick'>
<?php echo $this->Html->image('tick.png', array('width'=>'25', 'height'=>'25'));?>
</div>
<div class='amount'>
<?php echo $key['ProductPlan'][$i]['name'];?>
</br></br>
</div>
<div>Create Up To:<?php echo $key['ProductPlan'][$i]['limit'];?></div></br>
<div>Product Plan Amount:<?php echo $key['ProductPlan'][$i]['product_plan_amount'];?>.$</div></br>
</div>
</div>
<?php }?>
<?php } ?>
<?php } ?>
</td>
</tr>
<tr>
</tr>
</tbody>
</table>
I'm not sure I understand what you're asking, would this solution help?
http://jsfiddle.net/rG6bF/1/
$(":checkbox").click(function(e) {
$.each($(":checked"),function(idx,chkbox) {
log($(chkbox).attr('id'));
});
});
It would make it easier to help you if you could provide the HTML-output instead of the PHP-source.
If you want to target all checked checkboxes, and perhaps their relative email input fields, you could use something like this:
var email_arr = new Array();
$('input:checkbox:checked').each(function() { //goes through each checked input box
email_arr.push($(this).siblings("input.email").val()); //Gets the value of an email input field
});
The important thing is how you place the email input-field. If it's not in the same element as the checkbox, you might need to traverse up a node or two using .parent or .parents.
Hope that helps,
//Somersault

Categories