My php script creates a table with a list of courses and buttons in each row. Each set of buttons should obviously do the same thing, but for that particular row. Each row contains a button with class='add_button', class='wait_button' and class='detail_button'. The value for each button is the courseID of that particular row. This script is sent back to the main page via ajax, and inserted in the middle of the page.
When I click on one of these buttons, I would like to trigger a basic jquery event to test that each button is properly set. However, my current code does not seem to be working. I saw this in a similar post, tried the solution, and still got nothing. Therefore, I have left my initial script. Thank you for any and all suggestions.
courseDb.php:
while($row = mysqli_fetch_array($findCourses)){
echo "<tr>".
"<td><h3>" . $row['courseDept']. $row['courseNumber']. "-".$row['courseSection']."</h3>".
"<p>" . $row['courseName']."</p>".
"<td><p>Course Capacity: " . $row['courseSize']."/". $row['courseCurrent']."</p>".
"<p>Waitlist Capacity: " . $row['waitSize']."/". $row['waitCurrent']."</p></td>".
"<td><button class='add_button' value='".$row['courseID']."'>Add to Schedule</button></td>".
"<td><button class='wait_button' value='".$row['courseID']."'>Add to Waitlist</button></td>".
"<td><button href='#coursesDetailStud' class='detail_button' value=".$row['courseID'].">View detail</button></td>".
"</tr>";
}
courses.php:
$(".add_button").click(function(){
var clicked = $(this);
alert(clicked.val());
});
This script is sent back to the main page via ajax, and inserted in the middle of the page.
It seems to me that these rows (and the buttons) are returned by AJAX and is created after the page has been loaded.
As usual, any script placed directly in PHP or HTML files are executed on page load. If you simply use click method, it only bind the events on the elements already existing in the page, and have no effect if the HTML elements are added later by AJAX and DOM manuipulation.
You will need on with delegation, to make your event be bound even for elements loaded afterwards. (Assuming the parent table exists in the HTML/PHP)
$('table').on('click', '.add_button', function(){
//your code
});
Related
I am using this code for refresh my main DIV in my main page (named readings.php):
jQuery(document).ready(
function intervalle() {
setInterval(jQuery('#myMainDiv').load('readings_content.php'), 10000);
});
In the readings_content.php, sensor readings are being checked from database and drawing a screen like a security cam screens according to the sensor count. This code is like:
$db_sensors->query("select * from tbl_sensors where status=1");
if ($db_sensors->recordcount>0){
while ($db_sensors->nextrow()){
$sensors=$db_sensors->fields;
$sensorname = $sensors["name"];
$sensorvalue = $sensors["lastreading"];
echo "<div>";
echo "Sensor Name: ".$sensorname."<br>";
echo "Last Reading: ".$sensorvalue;
echo "</div>";
}}
This idea is working fine. But because of this loop (there are 9-16 sensors) refresh is taking time. That is normally fine because page is not reloading, just changing the values when it reads a new sensor reading. But there is a button in the my main page (readings.php). It takes almost 10 second for response time for this button even I am using local database.
I want to make this refresh process faster. Or if that is possible, I want to stop this refresh thing (or what ever is happening in the page) when I click the button. and make its onClick event working.
After my whole researches I started to try all different options. And it only was OK when I change the jQuery code like this:
setTimeout('sensorcells_load()', 10000);
function sensorcells_load()
{
jQuery('#sensorcells').load('dashboard_content.php');
setTimeout('sensorcells_load()', 10000);
}
I am not a jQuery man and I don't really know why this one works but other one doesn't. But this solved my issue.
I created a page which gets filled by a php databasequery (all rows are being read from the MySQL-table and written to the table in HTML). All 10 seconds the same PHP-script gets requested by jQuery AJAX and should refresh the current table content. The return-value of this function will then be used to change the table HTML-value.
There are some buttons in the table. When they're clicked, they toggle from on to off (or vice versa) and another PHP-file gets called with AJAX, which then controls 433MHz wireless sockets via shell commands. Purpose of these 10-seconds ajax-refresh is to synchronize the button with the actual state of the electrical socket (which is saved in the MySQL-database).
$(document).ready(function(){
$(".toggle").click(function() {
if($(this).hasClass("ein")) {
$(this).removeClass("ein");
$(this).html("aus");
$.post("various/executeCode.php", {transmitted:true, id:$(this).attr('id'), toggle:'0'}, function(result) {
});
} else {
$(this).addClass("ein");
$(this).html("ein");
$.post("various/executeCode.php", {transmitted:true, id:$(this).attr('id'), toggle:'1'}, function(result) {
});
}
});
});
window.setInterval("reloadPage()", 5000);
function reloadPage()
{
$.get('various/reloadPage.php', function(data) {
$("#content").html(data);
});
}
$stmt = $dbh->query("SELECT * FROM `funksteckdosen`");
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r)
{
echo "<tr>";
echo " <td>" . $r['name'] . "</td>";
echo " <td><button id='" . $r['id'] . "' class='toggle" . ($r['toggle'] == 0 ? "" : " ein") . "'>"
. ($r['toggle'] == 0 ? "aus" : " ein") . "</button></td>";
echo "</tr>";
}
Now I have the following problem: As soon as the page gets refreshed by AJAX the first time, the buttons stop working. Javascript doesn't execute the click()-function anymore. Why is that?
Problem 2:
The content of the table gets deleted and replaced by the new one. Am I somehow possible to fade new lines (or the button background-color) in, instead of just showing them? That would be the final touch.
I hope you understood my explanations.
The click handlers don't work anymore because the new buttons never had the handlers attached to them. When you attach a handler like this:
$(".toggle").click(function() {
What jQuery does is find all of the currently existing .toggle elements and, for each one, add that function as a handler. Since the new ones are added later via an AJAX call, they're not included in that set and, thus, never have that function attached to them.
The way jQuery address this is with the .on() function. The structure of using is it very similar:
$('body').on('.toggle', 'click', function() {
The difference here is the element which is actually getting the click event bound to the function. With this, the click event is actually being added to the body tag, which isn't changing from the AJAX call. Any unchanging common parent for the dynamic elements will work, 'body' and document are usually used as defaults since they're pretty top-level.
When any child element raises a click event, that event continues up all of the parent elements. So it eventually reaches a common parent, such as 'body'. The .on() function then also has a second selector as its first argument. That selector filters the originating elements of the click event before calling the function.
Benefits of using this approach include:
There's only one event handler function attached to a single common parent, instead of many attached to many elements, which can be a performance improvement on large or complex pages.
Child elements added to the common parent element later in the page's lifespan are still handled, since they will still send their click events to the parent regardless of when they were added. (This is the immediate benefit in your situation.)
As for fading in the content, if I understand the effect you're looking to achieve, you can try something like fading out what's already there, removing it, adding the new content, and then fading it in. Maybe something like this:
$.get('various/reloadPage.php', function(data) {
$('#content').fadeOut(400, function() {
$("#content").html(data);
$('#content').fadeIn();
});
});
There might be newer structures to accomplish this same thing with the relatively newer "promises" model, but essentially what this does is fade the content out and then include a call-back function to call when it's finished fading out. That call-back function replaces the HTML and then fades it back in. Depending on the structure of your HTML you might need to fade out/in a parent element instead of the one I'm targeting, but hopefully you get the idea here and can tweak it until it looks right.
Problem 1: The click event handler is bound to the initial toggle class elements but dynamically created events are not bound.
Try using live() or on() to bind dynamically created elements. See: Event binding on dynamically created elements?
Problem 2: #content is replaced when using html()
Try using append() to add data into an existing element. Using html() will replace the contents of the element.
I have chained a hide() and a fadeIn() to animate the append.
$('#content').append(data).hide().fadeIn(1000);
I have a PHP script that queries a database and returns the rows as li elements to a div in a jQuery Dialog. It does this by building an array in the PHP while loop that processes the query row responses. So far, so good. It displays a set of rows inside the Dialog in a div with an id=dialogResponse . It is the first two parts (2 rows of code) of the array instruction below. BTW, it is just li elements - there is no ul.
Now, I want to put a jQuery Button in each li response to give the user an action choice to inactivate/pause that posting. I'm pretty new at this, and I can't get a button to appear or anything to work. I get an Internal Server Error message so I can't tell if it is a selector problem, php syntax, or something else.
How do I get a jQuery button at the end of each li that will be the trigger point for a function that takes action on that row in the database? The event.preventDefault is a placeholder for a future function that will do a MySQL UPDATE on the selected streetAddress and city. Here's the code.
$messages[] = "<li>
$storedStreetAddress, $storedCity
"<script type="text/javascript"> $(function() { $( "#dialogResponse li")
.button( label: Pause posting).click(function( event ) event.preventDefault();});});
</script>"
</li>";
Please be specific and code helps a lot. I don't follow general instructions well in this area.
Why does the <script> have to be printed in with the PHP? Why not have it included with in a JS file? For the button, why not create a standard HTML [or whatever your preference] in each <li> and have jQuery target them for the actions? - You will need an <a>, <input>, <button>, etc. for the .button()
I'm trying to call a JavaScript function through PHP and have met some problems. I have got three code snippets for your understanding:
1) My javascript function:
function addPoints(radiobutton){
//code
}
The parameter is an actual button and inside the function is a lot of code reading button value and name and taking care of checked status of the button.
2) My php-code creating the button looks like this. Notice that i send 'this' to the function.
echo "<input type=\"radio\" name=\"X\" value=\"Y\" onClick=\"addPoints(this)\"/>";
3) Finally I have this code at the very end of the document for triggering the javascript function when page is loaded.
echo "<SCRIPT LANGUAGE='javascript'>addPoints();</SCRIPT>";
If addPoints only consisted of an alert, this would work. But my problem is that I need to send an actual button as parameter to the function. I need both triggering the function on page load (to load some data from a database) and the normal button onClick-event.
Is there any solution for this if I don't use another server request to catch the desired button? It's important that I get the button created above (in fact I've got a lot of buttons, but let's think of is as one) and send it as parameter.
Give the button to pass to the function on load an id="initial_radio_button" attribute, and then make your last snippet:
echo "<script type='text/javascript'>addPoints(document.getElementById('initial_radio_button'));</script>";
Specific questions are at the end of this (very long) pre-amble. Sorry, I tried to make it as short as poss. (took over an hour to write the question).
A .php file uses a (php) function to read rows in a SQL db and dynamically create an HTML table.
For each row, the SQL data is returned via $book['id'], $book['code'], $book['description'], etc.
The $book['code'] is a two-char alpha-numeric ID, eg. B7 or DW
In the HTML for each row is a <td></td> containing an anchor tag with an onclick= event that runs a JQuery script (to show/hide elements for that row).
Suppose a couple or rows were clicked and a couple of elements were hidden by the embedded JQuery script (which is working correctly, by the way)
When the user views a different page and then returns to this one, hidden elements (that were hidden by the JQuery script) are no longer hidden.
I wish to preserve a string of $book['code'] values for each clicked row an d, upon return to the first page, parse that string to reset the hidden elements.
<?php
function render_row_from_mysql() {
$output .= '
...create header row...
foreach ($books as $book)
{
create table row cells 1, 2, 3, 4
after cell 4:
<td>
<a id="addToShelf.php" onclick="
jQuery.ajax(\'./addToShelf.php?id='.$book['id'].'ats'.'\');
jQuery(addToShelfLink'.$book['id'].')[0].style.display = \'none\';
jQuery(rfs'.$book['id'].')[0].style.display = \'block\';
jQuery(mt'.$book['id'].')[0].style.display = \'none\';
jQuery(grn'.$book['id'].')[0].style.display = \'block\';
return false;
">
add to bookshelf
</a>
</td></tr>' ;
}
}
Questions:
Why doesn't the JQuery code above, which works correctly, need closing parentheses?
What is the syntax for creating/updating a var, in the anchor tag, that would preserve the cumulative clicked-row data? I ask because my many attempts all break the code.
Should the var be initialized at the top of the function, before the foreach loop?
I tried using PHP to create/update a cookie by inserting the following code after "return false;" (see below). The below php code does create a cookie when pasted into a separate script for testing.) The php code does not fire. Why?
The answers are:
1) Still not sure, just syntax.
2) As mentioned in Q4, I had been entering code AFTER the "return false;" statement, which is what concludes the onclick event. Therefore, any code placed after "return false;" would not fire as part of the onclick event... and there was nothing else to MAKE it fire.
3) Irrelevant
4a.) The above code is created within a PHP code block -- one cannot create a PHP code block inside JQuery inside HTML that is being created by (i.e. already inside) PHP.
4b.) Further to answer (2), my alert() tests would not fire because they followed the "return false;" statement,
4c.) Any new PHP code must be moved out of the HTML and placed back with the rest of the PHP, such as above the function(render_row_from_mysql){}.
It is now "back to the drawing board" to figure out how to preserve the "clicked items" data between when a user leaves this page and when he returns back to it. At this time, I suspect that will be some kind of a FORM $POST event, but having never done one before I'm not sure what that will look like.
I completely agree with Bjorn comment from 22 minutes ago. You need to remove all that onclick code and add a identifying class to your anchor tags. You sure also make sure that each HTML element has a unique id, it is a W3C validation requirement. If each book's id is unique system wide I would use that, see Example below:
<?php
function render_row_from_mysql() {
$output .= '
foreach ($books as $book)
{
//create table row cells 1, 2, 3, 4
//after cell 4:
<td>
<a id="'.$book['id'].'" class="addToShelf">
add to bookshelf
</a>
</td></tr>' ;
}
}
Add this javascript code to the bottom of your HTML code.
jQuery(document).ready(function($) {
// bind event to all anchor tags with class addToShelf
$('a.addToShelf').click(function() {
var book_id = this.id;
$.ajax('addToShelf.php?id='+book_id, function() {
// execute code after the ajax request is complete...
$('addToShelfLink'+book_id).hide();
$('rfs'+book_id).show();
$('mt'+book_id).hide();
$('grn'+book_id).show();
});
return false;
});
});