Ajax load() loads only once [duplicate] - javascript

This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 4 years ago.
I have a school project of making some page, which have to add, remove, modify and sort data from mysql. And i need, to refresh section 3 called "jezdci" or just the table in it. I using load() for that. But its loads only once, when i click on that a second time, nothing happend. Then i have to again refresh the page. And i need to load it again and again. Do someone know, where is a mistake?
You can see it at http://188.75.190.236/host/xhrazd7/www/ZP%20Hrazdira/index1.php
HTML:
<section>
<?php include "vypis.php"; ?>
</section>
JS:
$(document).ready(function(){
$(".serad > td").click(function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
PHP:
<?php
include "conn.php";
if(!empty($_POST["serad"])){
$serad = $_POST["serad"];
echo "<script>alert(\"variable succefully sended to PHP with value of \"+$serad);</script>";
}else{
$serad=8;
}
if($serad==0) $SQLprikaz = "SELECT * FROM ZP ORDER BY ID";
if($serad==1) $SQLprikaz = "SELECT * FROM ZP ORDER BY jmeno";
if($serad==2) $SQLprikaz = "SELECT * FROM ZP ORDER BY prijmeni";
if($serad==3) $SQLprikaz = "SELECT * FROM ZP ORDER BY vek";
if($serad==4) $SQLprikaz = "SELECT * FROM ZP ORDER BY bydliste";
if($serad==5) $SQLprikaz = "SELECT * FROM ZP ORDER BY ulice";
if($serad==6) $SQLprikaz = "SELECT * FROM ZP ORDER BY kategorie";
if($serad==7) $SQLprikaz = "SELECT * FROM ZP ORDER BY zaplaceno";
if($serad==8) $SQLprikaz = "SELECT * FROM ZP";
$result = $conn->query("$SQLprikaz");
echo "<table>";
echo"<tr class=\"serad\"> <td><p>Pořadí</p></td> <td><p>Jméno</p></td> <td><p>Příjmení</p></td> <td><p>Věk</p></td> <td><p>Bydliště</p></td> <td><p>Ulice</p></td> <td><p>Kategorie</p></td> <td><p>Zaplaceno</p></td> </tr>";
while($zaznam=$result->fetch_array(MYSQLI_NUM)){
echo"<tr> <td>$zaznam[0]</td> <td>$zaznam[1]</td> <td>$zaznam[2]</td> <td>$zaznam[3]</td> <td>$zaznam[4]</td> <td>$zaznam[5]</td> <td>$zaznam[6]</td> <td>$zaznam[7]</td> </tr>";
}
echo "</table>";
?>
And sorry for my poor english :D
PS: Když by se tu našel někdo hodný z Česka nebo Slovenska a měl chvíli času, budu rád, když mě zkontaktujete. Dík < some boring notes in my native language
and Thanks a lot!

As haï_uit mentioned it's because there's no event attached to the next table. You can get around this by targeting an element that will always be in the page and using the on Method like so:
$(document).ready(function(){
$("body").on("click", ".serad > td", function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});

The problem is here :
$(document).ready(function(){
$(".serad > td").click(function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
After your ajax load successfully, your old table which has "td" attached to click event is replaced by new table which doesn't have "td" with click event. So in your ajax load function, you must add click event for your table again after it load successfully. Another solution is just replace the data rows, not the whole table.
First option, you can add the click event again :
$(document).ready(function(){
var tabs = $('.serad > td');
tabs.click(changeTabs);
function changeTabs() {
y = $(this).index();
$('section:eq(2)').load('vypis.php',{
serad:y
}, function () {
tabs = $('.serad > td');
tabs.click(changeTabs);
});
}
}
Second option, only load table content:
Change your html file to this :
<section>
<table>
<tbody id="tabs">
<tr class="serad">
<td>
<p>Pořadí</p>
</td>
<td>
<p>...</p>
</td>
</tr>
</tbody>
<tbody id="content">
<?php include "vypis.php"; ?>
</tbody>
</table>
</section>
in php file, only echo the rows :
while($zaznam=$result->fetch_array(MYSQLI_NUM)){
echo"<tr> <td>$zaznam[0]</td> <td>$zaznam[1]</td> <td>$zaznam[2]</td> <td>$zaznam[3]</td> <td>$zaznam[4]</td> <td>$zaznam[5]</td> <td>$zaznam[6]</td> <td>$zaznam[7]</td> </tr>";
}
and finally, in your script :
$(document).ready(function() {
$('.serad > td').click(function () {
y = $(this).index();
$.post('vypis.php', { serad: y }, function (response) {
$('#content').html(response);
});
});
});

Related

How to use PHP - AJAX with mouseover event?

I have this levelselector.php page, where players can pick one of the levels. This works fine, but I want to add an extra thing. The table of the levels shows the level name, the difficulty, the count of completers (solved), and if the actual player has completed it.
This is the table with the levels
Here's what I want to do with AJAX: If I move the mouse over the CELL which shows how many players have completed the map, I want a little DIV that follows the mouse to show who the completers are. I already have the div which only appeares when the player moves over the "Solved" CELL, but I want to fill this "div" with the completers of the actual map. These completers are stored in a database, in which all the levels are stored with all their parameters, in another file, it doesn't matter.
This is the div which I want to fill with the actual level's completers
I was thinking this way: with Javascript I get the name of the Level name by getting the first "TD"-s innerHTML, and if I could give this name to PHP it would fill the DIV with the completers of the level the mouse over on is.
Here is my script.js code:
function delegate(parent, selector, type, fn) {
function delegatedFunction(event) {
let handler = this;
let target = event.target;
const closest = target.closest(selector);
if (handler.contains(closest)) {
fn.call(closest, event);
}
}
parent.addEventListener(type, delegatedFunction);
}
delegate($("table"), "td[id=completed]", "mouseover", showCompleters);
delegate($("table"), "td[id=completed]", "mouseout", hideCompleters);
async function showCompleters() {
var cursorsdiv = document.getElementById("completers");
cursorsdiv.style.visibility = "visible";
var levelname = this.closest("tr").firstElementChild.innerHTML;
const formData = new FormData();
formData.set("name", levelname);
const response = await fetch('levelselector.php', {
method: "POST",
body: formData
});
const data = await response;
document.addEventListener('mousemove', function(e){
var x = e.clientX;
var y = e.clientY;
cursorsdiv.style.left = x + 20 + 'px';
cursorsdiv.style.top = y + 10 + "px";
} )
}
function hideCompleters() {
var cursorsdiv = document.getElementById("completers");
cursorsdiv.style.visibility = "hidden";
}
(I used this delegate function to add each lines of the table mouseover events)
And here is the levelselector.php's html table part:
<table id="levelsTable">
<tr>
<th>Level</th>
<th>Difficulty</th>
<th>Solved</th>
<th>Completed by me</th>
</tr>
<?php foreach($levels as $level): ?>
<tr id="level">
<td id="levelname"><?= $level['level'] ?></td>
<td><?= $level['difficulty'] ?></td>
<td id="completed"><?= count($level['completed_by']) ?></td>
<td><?php if(in_array($_SESSION['username'],$level['completed_by'])) {
echo "Yes";
} else {
echo "No";
} ?></td>
</tr>
<?php endforeach; ?>
</table>
<div id="completers"><?= CONTENT WITH THE ACTUAL LEVEL'S COMPLETERS ?></div>
<script src="./levels/script.js" type="text/javascript" charset="utf-8"></script>
This DIV with the "completers" id would be the div which displays the completers, according to which level you move the mouse over.
Aaand here is what I could figure out in the PHP part:
<?php
$levels = load_file("levels.json");
if($_POST) {
$levelname = $_POST['name'];
}else {
$levelname = "";
}
?>
But sadly I don't understand how this AJAX works.
The question: How do you properly use AJAX in this case to fill the DIV with different content each line of the table if the mouse is moved over?
Hope you understood my english, thanks for all your help, appreciate it!!!
Peter

Extract multiple values from a MySQL table into HTML

I want to get three values from a MYSQL table, and display them in a text area. I can get only one value. If it possible, I want to save this selector, because it is critical to my program.
JavaScript:
function getsteel() {
var material = document.getElementsByName("option");
if (material[3].checked == true) {
var g = document.getElementById("selector1");
var str = g.options[g.selectedIndex].value;
document.getElementById('kr').value = str;
}
}
HTML:
<td>k<sub>r</td></sub>
<td>
<input type="text" id="kr" disabled style="width:50px;">
</td>
<td>[MPa]</td>
PHP:
<?php
mysql_connect("localhost","root","");
mysql_select_db("db-user22777");
//query
$sql=mysql_query("SELECT * FROM steels ORDER BY id ASC");
if(mysql_num_rows($sql)){
$select= '<select id="selector1" disabled size="12">';
while($r=mysql_fetch_array($sql)){
$select.='<option value="'.$r['kr'].'">'.$r['Steelname'].' | '.$r['kr'].' [MPa]</option>';
}
}
$select.='</select>';
echo $select;
?>
Thanks for any help provided!

HTML / JQuery: Email an Entire Div/Table

I want to be able to email content such as a div that is in my webpage using the php mail function and possible putting it on the so called "Thank Your, Your Email Sent" page. However, I'm running into some issues. I am following this Email Div Content, Email div text content using PHP mail function, and GET entire div with its elements and send it with php mail function questions that has already been posted as a guide but it doesn't seem to be working for me. I want to send via email and show up on the "Thank Your, Your Email Sent" page within the message. Anything I'm doing wrong?
HTML Table that I want to send over is:
<div id="add_items_content" style="width:100%;">
<center>
<table id="add_item_here" style="width:98%;">
<tbody>
<tr><td>Item</td><td>Years</td><td>Quantity</td><td>Training Hours</td><td>Total Item Cost</td></tr>
</tbody>
</table>
</center>
<center>
<table id="add_totals_here" style="width:98%;">
<tbody>
<tr><td cospan="3"> </td><td> </td><td> </td></tr>
</tbody>
</table>
</center>
</div>
<script>
$(document).ready(function(){
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
$('div[id^=show_form]').hide();
//First obtaining indexes for each checkbox that is checked
$('input[name=item_chk]').change(function(){
var index = this.id.replace('item_chk','');
if($(this).is(':checked')){
AddNewItem(index);
}else{
RemoveItem(index);
}
CalculateTotals();
});
function AddNewItem(index){
// Get hidden variables to use for calculation and tables.
var item = $('#item_chk'+index).parent().text().trim();
var itemdescr = $('#itemdescr'+index).val();
var traininghrs = parseInt($('#traininghrs'+index).val());
var qty = parseInt($('#qty'+index).val());
var yrs = parseInt($('#yrs'+index).val());
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
//Display each item that is checked into a table
$('#add_item_here tr:last').after('<tr id="row_id'+index + '"><td style=\"width:35%;\">' + itemdescr +'</td><td style=\"width:15%;\" >' + yrs +'</td><td style=\"width:16%;\">' + qty +'</td><td style=\"width:18%;\">' + traininghrs + '</td><td style=\"width:16%;\">$'+ item_cost + '</td></tr>');
}
function RemoveItem(index){
$('table#add_item_here tr#row_id'+index).remove();
}
function CalculateTotals(){
var total_cost = 0;
var total_training = 0;
$('input:checkbox:checked').each(function(){
var index = this.id.replace('item_chk','');
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
total_cost +=item_cost;
total_training +=traininghrs;
});
if(total_cost > 0 || total_training > 0) {
$('#add_totals_here tr:last').children().remove();
$('#add_totals_here tr:last').after('<tr ><td colspan="3" style=\"width:66%;\">TOTALS:</td><td style=\"width:18%;\">' + total_training + '</td><td style=\"width:16%;\">$'+ total_cost + '</td></tr>');
$('#add_item_here').show();
$('#add_totals_here').show();
$('#office_submit').show();
}else{
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
}
}
$("input[name='office_submit']").click(function () {
$('#show_form').css('display', ($(this).val() === 'Yes') ? 'block':'none');
});
// Quantity change, if someone changes the quantity
$('select[name=qty]').change(function(){
var index = this.id.replace('qty','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
// Years change, if someone changes the years
$('select[name=yrs]').change(function(){
var index = this.id.replace('yrs','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
})
</script>
Trial Number 1; So far I have tried:
<script>
function mail_content() {
var tablesContent = document.getElementById("add_items_content").innerHTML;
$.post('send_form.email.php',{content:tablecontent},function(data) {
});
}
</script>
Using script I have added to the send_form_email.php:
<?php
$txt = $_POST['content'];
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
?>
Trial Number 2: I even tried storing it into a hidden field:
<input name="data" id="data" type="hidden" value=""></input>
<script type="text/javascript">
$(document).ready(function(){
$("#price_quote").submit(function() { //notice submit event
$("#my_hidden_field").val($("#add_items_content").html()); //notice html function instead of text();
});
});
</script>
And then the send_form_email.php I put it in that message see if it even shows up.
$txt = $_POST['data'];
$message = "Content: ".$txt."\n";
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
Trial Number 3: Even tried Ajax
<script>
function mail_content(){
var html = $('#add_items_content').html();
$.ajax(function{
type="POST",
url:"send_form_email.php",
data:"data="+html,
success:function(response){
$('#add_items_content').show().html("email sent");
}
});
}
</script>
What am I missing or doing wrong? Why doesn't the div / tables show up or display?
You really should check your JS console for errors:
var tablesContent = document.getElementById("add_items_content").innerHTML;
^---note the "sC"
$.post('send_form.email.php',{content:tablecontent},function(data) {
^--note the c
JS vars are case sensitive, and will NOT magically correct typos for you.
And then there's this:
<input name="data" id="data" type="hidden" value=""></input>
^---id 'data'
$("#my_hidden_field").val($("#add_items_content").html());
^--- completely DIFFERENT ID

Show/hide by post id

I use some script to hide full content , but i have problem this only hide my first div in while.
script:
$('#blah').css({height:'20px', overflow:'hidden'});
$('#blah').on('click', function() {
var $this = $(this);
if ($this.data('open')) {
$this.animate({height:'20px'});
$this.data('open', 0);
}
else {
$this.animate({height:'100%'});
$this.data('open', 1);
}
});
And while php code , just wanna to show all rows from database and all result from db must to be hidden not just the first one..
PHP code:
$fq = mysqli_query("SELECT * FROM `table` ORDER BY time DESC LIMIT");
while($f = mysqli_fetch_array($fq)){
echo "
<div id='blah'>$link</div>
";
}
I just wanna to all results from db be hidden and can be ellapsed by postid , anyhelp?
Best regards
Selecting elements via jQuery using ID only selects the first occurence.
If you want to select many elements, dont use ID, use Class
while($f = mysqli_fetch_array($fq)){
echo "
<div class='blah'>$link</div>
";
}
On you script :
$('.blah').css({height:'20px', overflow:'hidden'});
$('.blah').on('click', function() {
var $this = $(this);
if ($this.data('open')) {
$this.animate({height:'20px'});
$this.data('open', 0);
}
else {
$this.animate({height:'100%'});
$this.data('open', 1);
}
});

Show/Hide Child Nodes using jQuery

I am trying to show child nodes(If option selected is 'Yes') based on the indent value. indent0-> parent node , indent1 - child node.
Sort-order is the order in which nodes are placed in DB.
$( "body" ).on( "click", ".js-show-aspects", function(event) {
var displayLabel = $(this).data('meta-value');
var sort_order = $('.js-data-selector.active:first').data('sort-order');
var indent = $('.js-data-selector.active:first').data('indent');
var rowCount = $('#show_aspects td').length;
for (var i=0;i<rowCount;i++)
{
var hasindent0 =$(this).next().hasClass("indent0");
if((displayLabel=='Yes') && (hasindent0== false)) {
child1 = $("table tr td").filter(function() {
return $(this).prop("class").match(/indent/)});
child = child1.addClass(function (index){ return "sort-order"+(sort_order+1)});
}
}
});
HTML
In the below html, $aspects gets all the nodes from DB,
<tbody>
<? foreach($aspects as $a) { ?>
<tr id="show_aspects" class="js-data-selector
<?=($a['active'] == 0) ? "text-warning" :""; ?> "
data-sort-order="<?= $a['sort_order'] ?>"
data-indent="<?= $a['indent']?>" align="left"
data-taxonomy-id="<?=$a['taxonomy_id']?>">
<td class="indent<?=$a['indent']?>
sort-order<?=$a['sort_order']?>"
data-indent="<?= $a['indent']?>">
<? if($a['active'] == 0) {
echo '<strong class="pull-right text-warning">Inactive</strong>';
} ?>
<?=$a['aspect_label']?> :
<span class="aspect-data" data-taxonomy-id="<?=$a['taxonomy_id']?>"></span>
</td>
</tr>
<?}?>
</tbody>
But I am unable to get the child nodes displayed. Any idea how to sort this out?
Edited the question with the HTML content..
It is difficult to understand exactly what you are trying to do with the question in its current form, but if you want to hide or show child nodes with jQuery, it can be done with $("#id").children().hide(); and $("#id").children().show();.
(Where "#id" is the ID of the parent DOM node.)
children() also takes a selector as an argument in case you only want specific children hidden/shown: http://api.jquery.com/children/
(If you clear up your question a bit, it would be possible to give a more appropriate answer)

Categories

Resources