I have created a jsfiddle for the following problem. I have tried to recreate it but it is hard because the data is being displayed server-side with PHP from a MySQL database.
I have a table and I am trying to pass the clicked <td> content into my modal box. If it doesn't have any, the modal box should appear with the user id but the input boxes are empty.
For some reason, the user id changes fine but the start time and end time inputs don't! Also, when I inspect the element it displays 8 - 5 for all the users? Does anyone have any idea why this is happening?
php code with the click + data params
for($dow = 0; $dow <= 6; $dow++) {
?><td class="js-clickable" data-user_id="<?php echo $user_id; ?>" data-start_time="<?php echo $row['st']; ?>" data-end_time="<?php echo $row['et']; ?>"<?php
if (array_key_exists($dow, $list)) {
foreach ($list[$dow] as $row) {
if ($row['user_id'] == $user_id) {
echo date("H:i", strtotime($row['st'])) . " - " . date("H:i", strtotime($row['et']));
The problem is with your PHP code as the HTML markup shown in the fiddle clearly shows that the data-end_time and data-start_time for Michael is shown as data-end_time="2015-03-27 17:30:00" data-start_time="2015-03-27 08:30:00".
There might be some error in the values fetched from the database. Make sure that you retrieve the values from the database correctly.
The jquery that you have written works perfectly in this case.
This is a PHP issue, because it was written at the PHP.
Now why it happens like that may be at date("H:i", strtotime($row['start_time'])) and I think the expected value($row['start_time'] and $row['end_time']) don't return a expected string to the strtotime function.
Check your code at this block and check how it is returned.
if ($row['user_id'] == $user_id) {
echo date("H:i", strtotime($row['start_time'])) . " - " . date("H:i", strtotime($row['end_time']));
}
I hope I've helped ya.
I've identified the issues with your PHP code that caused the data to be incorrectly populated in the table.
The main issue was to do with bad logic in the section that writes the tags. For example, the $row variable used to write the data attributes was entirely different from the $row variable used to write the contents of the TD. Also, you were writing the data attributes of the first TD tag before even looking for the schedule for that user. I revamped the code in that section so that the full TD tag is written in two areas, either with scheduled data, or without. The code is still pretty messy, but at least now it works. Also, on line 57 of the code in the pastebin you posted had a misplaced quote between the php closing tag (?>). It was: ?"> It should be: ?>"
A couple of smaller observations:
- Bootstrap CSS was linked twice (one local, one remote). Not part of the issue, just an observation.
- The closing tag for the form and the surrounding div were in the wrong order. Close the form before the div.
Here is the working code to correctly populate the data attributes and content of the table:
// Code removed at request of OP.
Related
i have over one hundred html files that all roughly have the same structure. the html files represent each page of a comic.
naturally, i've realized that it would be more efficient to apply the structure of these pages to one file, and allow that file to dynamically create all of the comic pages.
my goals are so that, one; when a user accesses a comic page, the page number that the link contained can be passed through as a number value to determine the image file and the url.
two; when a user clicks "next" or "previous", the number value that defines the page is either added to or subtracted by one to load in the new url & image file.
and three; for the "next" and "previous" buttons to define themselves/decide whether to appear or not based on a filecheck i've already written.
<?php
if ($_GET["img"]) {
$imgnum = $_GET["img"];
} else { $imgnum = 1; }
?>
<html>
<div class="block">
<?php echo '<img class="page" src="' . $imgnum . '.png">'; ?>
</div>
</html>
this code does the trick for changing the image file and url based on the value of $imgnum but when it comes to passing values into the "next" and "prev" buttons, i have no idea what the hell im doing. i tried doing THIS:
<?php $prevValue = $imgnum - 1?>
<h2 class="arrow">Previous</h2>
clearly, passing a variable into that key does not work. is there any way to preserve the dynamism of the buttons with this php method? these buttons need variables to work on their own. do i have to switch to jquery? i honestly above all else need advice on where to start. i barely understand what's going on in this php script itself.
<?php
if ($_GET["img"]) {
$imgnum = $_GET["img"];
} else { $imgnum = 1; }
?>
What the above does.....
If (the URL string contains the [img] value ) {
Get the value of [?img=] from the URL string...
i.e. index.php?img=4 .. (it is getting the 4)
and set the [$imgnum] variable to that value
} else {
But if the URL does NOT contain the [img=] value,
then set the variable value to 1 [$imgnum = 1;]
}
It's difficult to tell exactly what you want, but the below will add the value properly to the button.
<?php $preValue = $imgnum - 1; ?>
<h2 class="arrow">Previous</h2>
PHP lines end with a semicolon... and you have to echo variables for them to be output to the HTML.
I have no clue what jQuery and javascript have to do with your question. But yes.. this could all be handled by an ajax request and you wouldn't need to reload the page every time a button is clicked.
However, if you don't understand what the PHP is already doing, explaining how to do this via AJAX will be exceptionally confusing to you. And much more of your code structure would need to be seen.
You're creating the right code but you just forgot to echo it.
You need to change your line to;
<h2 class="arrow">Previous</h2>
or you can use the shorter version if your php.ini configuration allows to;
<h2 class="arrow">Previous</h2>
Note:
You should be aware of SQL injection and secure your get variables by;
$imgnum = (int)$_GET["img"];
As you are taking the $_GET value as a variable, this time, only integer values will work so hackers cannot inject a code.
So, here is the page in discussion, DONATION RESULTS
What I did was I used the SQL DB to populate rows by totals, works great. Now, I want when the name is clicked, or the ammount is clicked, for a dialog to pop up with all the individual donations that person has recieved. To do this, I need to use
$eachone = mysql_query("SELECT donor_first,donor_last FROM dc_donations WHERE sponsoring='***'")
where * needs to automatically fill with the data from the name/previous query. So for example, for the sponsor tk, when you click on the link tk, it should run
SELECT donor_first,donor_last FROM dc_donations WHERE sponsoring='tk'
It also needs to be nested inside another while loop. This works, outside of the while loop, just as a test. It retrieves all the names, however, not just the ones for that particular sponsor. But, when I put it inside the other while loop, to put the content inside the div, instead of in some random spot on the page, it doesn't work anymore.
while($row=mysql_fetch_array($eachone)) {
echo $row['donor_first'] . ' ' . $row['donor_last']. ' ';
}
here is my entire code, sorry if its long, shouldnt be too bad.
MY CODE (PASTEBIN)
At Line 71, shouldn't you supposed to close </a> before </td>?
I recommend to check HTML generated to see what happened, if PHP isn't coming with error.
Give us more information to provide a better help.
In line 63 you have opening <tr> tag but it have no closing </tr>
I’ve just started learning PHP and have attempting to build my first data driven web page to aid with my learning but I now seem to have come across a problem that's been driving me nuts.
Here is a bit of background.
What I have been attempting to do is pull content from a database, this content is already marked up with html paragraph tags. The content will be user submitted and so I have no way of knowing how many paragraphs each row will contain.
I am then looping through the content and counting the paragraphs so that I end up with 5 paragraphs inside each containing div.
Here is the code I am using to do this, I know my code is a bit basic but it seems to work fine as long as all of the content is retrieved in just a single query.
$stmt = $db->prepare('SELECT * FROM content');
$stmt->execute();
foreach($stmt as $row) {
$allParagraphs .= $row['content'];
}
$paragraphArray = explode("</p>", $allParagraphs);
$paragraphCount = 0;
echo '<div class="bookPage">';
foreach ($paragraphArray as $value) {
echo $value;
$paragraphCount = $paragraphCount + 1;
if ($paragraphCount == 5){
echo '</div><div class="bookPage">';
$paragraphCount = 0;
}
}
echo '</div>';
And now my problem.
Now I would like to include pagination with an endless scroll effect using PHP and Jquery. I feel confident enough to do this; however, I have noticed that the current code I am using (to count every 5 paragraphs) is not going to work when I introduce pagination.
As far as I can see, after working through the code what is going to happen is that the closing div is going to be inserted and then, when the 2nd query made via ajax (read more link clicked) it is going to result in a new opening div. This results in the leftover paragraphs from each query being surrounded by the div tag and not containing the 5 paragraphs I need.
Basically, in its simplest terms, what I would like to do is to still be able to wrap div tags around every 5 paragraphs but also still be able to paginate the results via ajax.
If anyone could advise me of the best way to go with this it would be very much appreciated.
My musings on this issue so far...
I am not sure if this is even possible to do which leads me to believe I have approached this the wrong way. I’m not very experienced at the moment but I can’t help think that it would be easier to store every paragraph in a separate row in the database which would allow me to then pull them out in multiples of 5. But then, something else is telling me that would not be a practical solution at all, especially as I have no way of knowing how many paragraphs each user would be writing/submitting.
I dont have enough points to post an image so here is a link to an image i uploaded in attempt to demonstrate what i mean should my attempt at describing the issue not be enough.
Diagram showing issue
Thank you in advance of any suggestions.
I guess you could remove all the HTML tags in your PHP script and just return the content of the paragraphs as JSON object, for example.
So, basically, you'd return something like:
echo json_encode($paragraphArray);
And request that with jQuery like this (which is an adoption of the first example at http://api.jquery.com/jQuery.getJSON/):
jQuery.getJSON('yourURL.php', function(data) {
var items = [];
jQuery.each(data, function(key, val) {
items.push('<p>' + val + '</p>');
if(items.length == 5) {
appendItemsToBody(items);
items = [];
}
});
appendItemsToBody(items);
});
function appendItemsToBody(items) {
if(items.length) {
jQuery('<div/>', {
'class': bookPage,
html: items.join('')
}).appendTo('body');
}
}
Depending on what should happen when clicking on "load more", you could pass the count of currently displayed items as data to the call to your PHP script via jQuery.getJSON() (see their API documentation) and then decide in your PHP script which paragraphs you should return (i.e. where to start from). You'd have to append the "rest" of the paragraphs to fill up the 5 items to the existing last div in jQuery, and put the rest into new divs.
SAME PAGE RESULTS: (xmain.php)
//FORM (working good)
<form name="search" action="xmain.php" method="post">
code,code,code,
// QUERY (working good)
code,code,code,
<input type="submit" name="doSearch" value="doSearch">
//These are last 2 lines of my 15 line query - I have skipped the rest to save space:
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM $tableName $qryWhere LIMIT $start, $limit;";
$result = mysql_query($sql);
// Table query results here.....
OK, although all code is working correctly ( Form is submitting variables, database results are correct, etc, there are 2 nagging problems:
1 - ALL database results are echoed when the page is first loaded. The page is refreshing from top to bottom without a stop in between - I would like for NO RECORDS to be shown at first page arrival.
2. Also, because of the top to bottom nature of this page,my option choices are being reset upon form submission. I would like to maintain selections until the RESET button -
that I have on the page for that purpose is clicked.
I realize that the form by always refreshing upon itself, is causing the above problems.
Any suggestions would be greatly appreciated! - see working sample here:
http://www.symbioticmusicpublishing.com/database3/xmain.php
Only show something when something is actually posted, so surround with if(isset($_POST['doSearch']){.. or something.
echo a value <input .... value="'.(isset($_POST['thisinputname'])?htmlspecialchars($_POST['thisinputname']:'')">
On more elaborate forms a session could be handy, not needed for simpler ones/forms always getting the post though. BTW, I prefer using GETs for listing data, makes it easier to share/link. POSTs for alterations, GETs for retrieving (and a few other methods for real REST).
Echo the retrieved values inside a if statement like Wrikken suggested. Check that your form submission button is actually clicked and only then echo the results.
If you're unfamiliar with the syntax take a look at ternary operator.
http://www.php.net/manual/en/language.operators.comparison.php
Also use GET if you are getting data from database. And POST when you are putting data into database. I guess the reason why goes beyond the naming convention but still it's a nice reminder: GET for getting and POST for posting/putting.
UPDATE
Sorry I didn't think this one through. Put the sql query inside a if statement. Put also the echoing of results inside a if statement.
if (isset[$_POST['doSearch']]){
//make the query
}
if ($sql){
//echo the results
}
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;
});
});