Adding values to tables with JQuery. Table created with PHP loop - php

I am trying to make a form which let you see boarding times per day.
The table is created with PHP. Having a row for every day of the week, except Saturday and Sunday:
<?php
for ($i = 1; $i < 8; $i++){
$d=strtotime("+".$i." Day");
if (date("l", $d) !== "Saturday" && date("l", $d) !== "Sunday" ){
$daydate = $dayOfWeek[date("l",$d)] . date(" d ", $d) . $month[date("F",$d)];
echo "<tr>";
echo "<td>". $daydate . "</td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "</tr>";
echo '<tr class="BoardingTimeMorning">';
echo '<td style="padding-left: 30px">
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input> <div class="time">0:00</div>
</td>
<td>
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input><div class="time">0:00</div>
</td>
<td>
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input><div class="time">0:00</div>
</td>
<td>
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input><div class="time">0:00</div>
</td>
</tr>';
}
}
?>
When someone selects their destination, the corresponding times need to show in the table above. Selection is done with AJAX request and returns the times in an array. No more than 4 boarding times are possible.
I am trying to get it working with JQuery, but nothing happens.
JQuery:
$('#boardingplace').change(function() {
$.ajax({
type: 'POST',
url: 'reservePage.php',
dataType: 'JSON',
data: {
'station': this.value
},
success: function(response){
var len = response.length;
console.log("length: "+len);
$( ".BoardingTimeMorning" ).each(function() {
for (var j=0; j<4; j++){
//visibitly off
var tdContent = $(this).find('.BoardingMorning'+j);
console.log (tdContent);
tdContent.css("display", "none");
tdContent.next().html("");
//reset value
tdContent.attr('value', "");
if(j - len <= 0){
//show content according to amount of times
tdContent.css('display', "block");
tdContent.attr('value', response[j].slice(0,5));
tdContent.next().html(response[j].slice(0,5));
}
}
});
}
});
});
What is the best way to get it to work?
EDIT:
Turns out I use 2 class definition on the input element. The bootstrap class and another for selecting it. I put them together and all works..
Thanks for all you help people! Really love this community!

There is an easy solution:
you can create a response.php file like this:
url used for example:
response.php?station=162
<?php
//response.php
$station=$_GET['station'];
$data_from_database=// your sql Request...
?>
<html>
<div class="datas">
<?php
foreach ($data_from_database as $data) {
echo "<span>".$data['time']."</span>";echo "<br>";
echo "<span>".$data['name']."</span>";echo "<br>";
}
?>
</html>
in your javascript you can load data from response.php file like this:
<script type="text/javascript">
$('#boardingplace').change(function() {
var station= this.value;
$.ajax({
type: 'GET',
url: 'response.php?station'+station,
success: function(response){
$(".BoardingTimeMorning").html(response);
}
});
});
</script>
and data will be loaded in div with class="BoardingTimeMorning"
I hope this could help you.

Related

Change specific dynamically created table row html and text from ajax response

From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>

How can i pass form loop values in ajax and get by php?

I have a form which contain radio buttons, which is in a loop. If the loop has 10 count, it will show ten set of radio buttons. I have a structure like below, so I need to get all the values and insert in the database.
HTML:
<form id="sendForm">
<?php
$n = 0;
for ($x=0; $x < count($q_id); $x++)
{
?>
How is our Services?
<label>
<input type="radio" name="Choice_<?php echo $n;?>" id="Choice_<?php echo $n;?>" value="poor"/>
</label>
<label>
<input type="radio" name="Choice_<?php echo $n;?>" id="Choice_<?php echo $n;?>" value="Bad"/>
</label>
<label>
<input type="radio" name="Choice_<?php echo $n;?>" id="Choice_<?php echo $n;?>" value="Good"/>
</label>
<label>
<input type="radio" name="Choice_<?php echo $n;?>" id="Choice_<?php echo $n;?>" value="VeryGood"/>
</label>
<?php
$n = $n+1;
}
?>
</form>
Here is how validation happen:
JavaScript:
var names = [];
$('input:radio').each(function () {
var rname = $(this).attr('name');
if ($.inArray(rname, names) == -1) names.push(rname);
});
//do validation for each group
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length == 0) {
$("#Error").after('<span class="error">Choose the above field</span>');
valid=false;
}
});
if(valid)
{
SubmitForm();
}
return valid;
Ajax:
function SubmitForm() {
var formdata = $('#sendForm').serialize();
$.ajax({
type: 'POST',
url : '/post_page.php',
data: formdata,
async: false
}).done(function(msg)
{
//Success or error
}
}
I got stuck now how to get each values of radio buttons selected and get by $_POST[] and save in database.

show dynamic checkbox when its parentcheckbox clicked (ajax,jquery)

i have two kinds of checkbox -> parent_checkbox and child_checkbox
when parent_checkbox checked then it should show its child_chekbox.
when i check last parent_checkbox first-> then i get its child_chekbox. and then check other parent_checkbox i get its parent_checkbox respectively.
but the problem is when i check first parent_checkbox for the first time ->i get its respective child_chekbox. but again i click other(2,3,4) parent_checkbox i still get
child_chekbox of first parent_checkbox and it for the rest of parent_checkbox getting same result.
HTML Part
<h5><p> parent</p></h5>
<?php foreach ($parentcheckbox as $parentcheckbox) { ?>
<input type='checkbox' name='name2[]' value="<?php echo $parentcheckbox["id"]; ?>" class="parentcheckbox" class="form-control" >
<?php echo $parentcheckbox['name']; ?>
<?php } ?>
<h5>child<h5>
<div class="hidden show_childcheckbox" style="margin-top: 14px;">
</div>
</div>
and the script
<script>
$('.parentcheckbox').click(function () {
var array = $("input[name2]").val();
var childcheckbox_html = "";
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/...",
data: $('#tab4 :input').serializeArray(),
success: function (response) {
$(response.childcheckbox).each(function (i, v) {
childcheckbox_html += "<input type='checkbox' name='name3[]' value='" + v.id + "' class='childcheckbox' class='form-control' >";
childcheckbox_html += "label ='" + v.name + "' "
});
$('.show_childcheckbox').append(childcheckbox_html)
$('.childcheckbox_html').show()
console.log("44")
}
});
});
<script>

I don't have access to the HTML's id that generate from php

I using AJAX and generate html code with PHP after I get answer from the DATABASE.
first part work greate, I am laoding data from the Data base and and create table of forms.
the issue is that I can't edit the use the IDs that create I tried to change TD size or call specific IDs with JQuery but nothing happen.
HTML
<html>
<head>
<title>תמונה במתנה</title>
<meta charset="utf-8">
<link href="admin-style.css" rel="stylesheet" type="text/css">
<script src="jquery.js"></script>
<script src="admin.js"></script>
</head>
<body>
<div id="container">
<div id="customer-list">
</div>
<button type="button" id="loadbtn">טען</button>
<div id="search">
<form id="searchForm" action="admin.php" method="post">
שם פרטי:<input type="text" name="fname" id="fname">שם:
שם משפחה:<input type="text" name="lname" id="lname">
טלפון:<input type="text" name="phone" id="phone">
אימייל:<input type="text" name="email" id="email">
<input id="searchForm" type="submit" name="searchbtn" value="חפש" />
</form>
</div>
<div id="serchList">
</div>
<div id="editCustomer">
</div>
</div>
</body>
</html>
JQuery:
$(document).ready(function() {
$.ajax({
url: 'loadClient.php?submit=load',
success: function(data){
$('#customer-list').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
$
$("#savebtn").click(function(){
alert ('hi)';
var lfname=document.getElementById('lfname').value;
var llname=document.getElementById('llname').value;;
var lemail=document.getElementById('lemail').value;;
var lcity=document.getElementById('lcity').value;;
var lphotos=document.getElementById('lphotos').value;;
var lid=document.getElementById('lid').value;;
$.ajax({
type:'POST',
url: 'loadClient.php ',
data: 'submit=save&lfname='+lfname+'&llname='+llname+'&lemail='+lemail+'&lcity='+lcity+'&lphotos='+lphotos+'&lid='+lid,
success: function(data){
$('#customer-list').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
$.ajax({
url: 'loadClient.php?submit=load',
success: function(data){
$('#customer-list').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
});
PHP
echo '<table border=1 cellspacing="0" cellpadding="0">';
echo '<tr>';
echo '<td width="80px">שם פרטי</td>';
echo '<td>שם משפחה</td>';
echo '<td>טלפון</td>';
echo '<td>אימייל</td>';
echo '<td>עיר</td>';
echo '<td width="150px">שעת רישום</td>';
echo '<td>מספרי תמונות</td>';
echo '<td>שמור</td>';
echo '</tr>';
$loadQuery="SELECT * FROM `claients` WHERE `eventreg_pictures` is null
OR `eventreg_pictures` like ''";
$result=mysql_query($loadQuery);
while($row= mysql_fetch_array($result)){
$client= $row;
$clients[]=$client;
echo '<tr>';
echo '<form id="loadForm" method="post" action="admin1.php">';
echo '<input type="hidden" name="lid" value="'.$client[0].'">';
echo '<td><input type="text" id="lfname" name="lfname" value="'.$client[1].'"></td>';
echo '<td><input type="text" id="llname" name="llname" value="'.$client[2].'"></td>';
echo '<td><input type="text" id="lphone" name="lphone" value="'.$client[3].'"></td>';
echo '<td><input type="text" id="lemail" name="lemail" value="'.$client[4].'"></td>';
echo '<td><input type="text" id="lcity" name="lcity" value="'.$client[5].'"></td>';
echo '<td>'.$client[7].'</td>';
echo '<td><input type="text" id="lphotos" name="lphotos"></td>';
echo '<td><input type="submit" id="savebtn" name="savebtn" value="שמור"></td>';
echo '</form>';
echo '</tr>';
}
echo '</table>';
}else echo'error';
If I'm right, the problem is that Your #savebtn doesn't exist when You define the $("#savebtn").click handler.
Try this instead:
$("#savebtn").ready(function(){
$("#savebtn").click(function() //...Continue Your code...
});
A few things:
'1. You're mixing up jQuery and javascript, when jQuery is simpler and shorter to type. This line:
`var lfname=document.getElementById('lfname').value;`
can be replaced with this line:
var lfname=$('#lfname').val();
'2. Your PHP is looping through results returned by a mysql search, but you are using the same ID for all returned rows. This is a no-no. Each ID must be unique. Edit your PHP code to add a unique number to each id name, based on row.
Try Something like:
$counter = 0;
$loadQuery="SELECT * FROM `claients` WHERE `eventreg_pictures` is null
OR `eventreg_pictures` like ''";
$result=mysql_query($loadQuery);
while($row= mysql_fetch_array($result)){
$client= $row;
$clients[]=$client;
echo '<tr>';
echo '<form id="loadForm-' .$counter. '" method="post" action="admin1.php">';
echo '<input type="hidden" name="lid" value="'.$client[0].'">';
echo '<td><input type="text" id="lfname-' .$counter. '" name="lfname" value="'.$client[1].'"></td>';
That way, in your jQuery, you can check to see - for example - which field was just completed:
$('[id^=lfname]').blur(function() {
var xx = $(this).attr('id');
alert('You edited input: ' + xx);
var arrYY = xx.split('-'); //turn xx into an array, separated at each hyphen
var yy = arrYY[1]; //The number part of the array
alert('The number part of this element is: [' +yy+ ']');
});
'3. Note that you can also select elements by class, so you could add a class to your lfname input fields, catch the blur (or focus, or etc) event on any element with that class, and determine exactly which input it was:
echo '<td><input type="text" id="lfname-' .$counter. '" name="lfname" value="'.$client[1].'"></td>';
$('.lfname').blur(function() {
var xx = $(this).attr('id');
alert('You edited input: ' + xx);
});
'4. To be clear, the reason nothing happens when you reference specific IDs on your page is because you have more than one element with that same ID. IDs must be unique. See #2 above to make the IDs unique, or just use the class attribute.
שלם

jQuery ajax script wont work with n number of forms from PHP

I have a little problem with my AJAX jQuery script and n number of forms...To be more precise, PHP script generate N number of forms (form include one textarea and one button), and in head tag I included jquery script. Problem is that jquery work only for first form and not with others (second, third...). I needed to work with all forms...This is the code:
<script>
$(document).ready(function() {
$("#submitForm").click(function() {
var text = $("#comment").val();
var id = $("#id").val();
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
And this is PHP code
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment'></textarea>
<input type='hidden' id='id' value='".$id."'/>
<input type='button' id='submitForm' value='Add Comment'>
</div>";
}
What is problem???
On your PHP side you should change with something similar to this to ensure that all the html elements has a unique id.
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment".$i."'></textarea>
<input type='hidden' id='id".$i."' value='".$id."'/>
<input type='button' id='".$i."' class='submitForm' value='Add Comment'>
</div>";
}
and change the Javascript with something similar to this to reflect the changes made on the php side
<script>
$(document).ready(function() {
$(".submitForm").click(function() {
var formNumber = $(this).attr("id"); // Get the form number that was clicked, the id attribute of the clicked button
var text = $("#comment"+formNumber).val(); // Get the comment of that particular form
var id = $("#id"+formNumber).val(); // get the id of that particula form
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
For every form you're creating you're using the same ID.
IDs must be unique and only appear once on the page.
You should use a class instead as suggested in the comments.
So more like this:
<?php for ($i = 0; $i < $num; $i++): ?>
<div>
<textarea class="comment"></textarea>
<input type="hidden" class="id" value="<?php echo $id; ?>">
<input type="button" class="submitForm" value="Add Comment">
</div>
<?php endfor; ?>
I'm not sure where your $id variable comes from.
Your JavaScript will need to be updated as well to work with this, I'd do something like this (elaborated so you can see what's going on):
$('.submitForm').click(function(e) {
e.preventDefault(); // stops the default form action (if there is one)
var $submitButton = $(this);
var $div = $submitButton.parent(); // gets the div container
var id = $div.find('.id').val();
var text = $div.find('.comment').val();
// now do your ajax
});

Categories