I'm not a developer but I've been dabbling around with this for a while. Hope you can help
I have several div's with ID:s that are given to them dynamically through php. I have a function that is called through a checkbox which hides and shows the divs. What I want to do now is to get the div ids from the document and put them into the function.
I've kind of copied codes from different forums and it works if I'm hard coding the div names. Not sure what I'm doing now though, any help would be appreciated.
Here's what I have
Assigns id's to the divs:
$a .= "<div id='$go[media_caption]" . $i . "'>";
The function:
var editorial = [id^='editorial']);
function visiblox(arrDiv, hs) {
var disp = (hs) ? 'none' : 'block';
for(var x = 0; x < arrDiv.length; x++) {
document.getElementById(arrDiv[x]).style.display = disp;
}
}
function chk(what, item) {
if(item) {
visiblox(what, false);
} else {
visiblox(what, true);
}
}
Calls the function:
<input type='checkbox' onclick='chk(editorial, this.checked);' checked> Editorial</p>
Can you have your PHP output an array for your Javascript to use? As PHP outputs the IDs, it would also add them to a string that is in the syntax of a Javascript array. Something like this:
$a .= "<div id='$go[media_caption]" . $i . "'>";
$jsIDs .= "'$go[media_caption]',";
Then at the end of the file, just before you the PHP file closes the </body> and </html> tags, output the array as a script:
$jsIDs = substr($jsIDs, 0, strlen($jdIDs)-1); // strip off the last comma
$jsIDs = "<script type='text/javascript'>var idArr = [" . $jsIDs . "];</script>";
echo($jsIDs);
Then inside the javascript, you don't need to look up the IDs in the DOM. You can just use the array (in my example, I called it idArr).
UPDATE: Martin says the IDs output by PHP sometimes start with "editorial", some start with something else. To collect only the ones that start with "editorial", change the line above that starts with $jsIDs .= to these two lines:
if ( substr($go[media_caption], 9) == "editorial" )
$jsIDs .= "'$go[media_caption]',";
That should do the trick.
Related
I am trying to use Parsedown Extra with Parsedown (Have never used either before). I have the code $_GET the selected category (?cat=0) and set it's path & filename to a var. It $_GETs the page number just fine, however when I set the file var, it just prints to the screen and doesn't load my page.
//sets the page (category) number for use with array
//also sets the path to the category's pages
if (isset($_GET['cat'])) {
$catNum = $_GET['cat'];
$catPath = 'content/' . $pageList[$catNum]['path'];
echo '<div class="center pageNav">';
//lists out subpages of catagory
$pageAmt = count($pageList[$catNum]['pages']);
for ($i = 0; $i < $pageAmt; $i++) {
echo '' . $pageList[$catNum]['pages'][$i]['title'] . '';
};
echo '</div>';
//sets path & filename var to selected page: this is the part where it prints the var and doesn't run the rest. The var is pointing to the right file, I checked.
$page = $catPath . $pageList[$catNum]['mainPage'];
} else {
$page = 'content/home.md';
};
//parsedown
require 'parsedown/parsedown.php';
require 'parsedown/parsedownextra.php';
echo ParsedownExtra::instance()
->setBreaksEnabled(true)
->setMarkupEscaped(true)
->text($page);
you have a semi colon at the end of your if statement.
} else {
$page = 'content/home.md';
}; <--
Parsedown takes marked up text and renders it. In your example, you pass $page (which holds a string, a filename) to ->text($page). This parses the string as marked up text, and renders it. So, in your example you are seeing exactly what it is doing. If you are trying to run the text of the file through ->text, you need to load the file contents first and pass to Parsedown.
I was trying to generate a Javascript varialbe using php. I am getting the desired result on the source page but it looks like that result is not being processed into the array. Is there any way of doing it using javascript? Here, I'm generating URLs for images that need to be displayed on my website carousel and though a for loop would save me the time of entering every url. The images are also number serially. Since I'm not well versed in javascript can you suggest me a javascript alternative?
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
You can do it using javascript only. No reason for using PHP here.
var leftrightslide = new Array()
var finalslide = ''; // this line is not really relevant to the question
for (var i = 0; i < 34; i++){
var j = i + 1;
leftrightslide[i] = '<img src="../images/'+ j +'.jpg" border="0">';
}
echo "leftrightslide[".$i."]='<img src=\"../images/".$j.".jpg\" border=0>';";
Here's a snippet of code that I use to move data from PHP To JS
if (isset($javascriptData)) {
echo "<script>";
foreach(array_keys($javascriptData) as $jsData) {
echo "var " . $jsData . " = " . json_encode($javascriptData[$jsData]) . ";\n";
}
echo "</script>";
}
I pass in $javascriptData to my view which is an array with the structure array('JS_VAR_NAME' => 'JS_VALUE')
You can then use those variables in any scripts you've added below that
Since your example code contains no script tags, or other HTML elements for that matter, one might assume that this PHP snippet is intended to generate some JavaScript source "file" external to the page in which it is being used.
If that is the case, consider that the following additional line may just fix it:
<?php header( 'Content-Type: text/javascript' ); ?>
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
My PHP script 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. Each li element has some data, an HTML button, and some javascript to execute on that li element when the button is clicked.
If I write "bad HTML" with the same id for each li element, the javascript executes, but only on the first li element. When I write "good HTML" with a unique id for each li element, I can't get the javascript to execute. I've researched and tried lots of things, but can't find anything this complicated to fix this. What should I do? Here's the stripped down code. The problem seems to be in the lengthy $error_ListActives line, but I'm open to suggestions.
$rowCount = 0;
while ($row = mysql_fetch_array($fetch)) {
$storedStreetAddress = $row["streetAddress"];
$storedCity = $row['city'];
$error_NumberOfActives = "<li>Welcome back. You have . . .</li>";
$errorMessages[0] = $error_NumberOfActives;
$idMaker = "inactive" . $rowCount;
$error_ListActives = "<li> $storedStreetAddress, $storedCity $idMaker
<button type='button' id=$idMaker onclick='makeInactive()'>Pause this</button>
<script type='text/javascript'>function makeInactive()
//do stuff
{document.getElementById($idMaker).innerHTML='Inactive Completed';}
</script> </li>";
$errorMessages[] = $error_ListActives;
$rowCount++;
}
foreach( $errorMessages as $statusMessage ) {
echo $statusMessage;
}
Please be specific, and code is helpful. I don't follow general instructions well in this area, as I'm a newbie with PHP.
You're going to end up with a lot of problems here because you are writing your javascript function inside a while loop. That means that you will get several copies of the same function, and only the last one is going to actually fire!
To fix this, write a generic javascript function for makeInactive(id) and then just call it with the id of the element you are working on.
Outside of the php loop:
<script type='text/javascript'>function makeInactive(id)
//do stuff
{document.getElementById(id).innerHTML='Inactive Completed';}
</script>
Then change the php loop to:
while ($row = mysql_fetch_array($fetch)) {
$storedStreetAddress = $row["streetAddress"];
$storedCity = $row['city'];
$error_NumberOfActives = "<li>Welcome back. You have . . .</li>";
$errorMessages[0] = $error_NumberOfActives;
$idMaker = "inactive" . $rowCount;
$error_ListActives = "<li> $storedStreetAddress, $storedCity $idMaker
<button type='button' id='$idMaker' onclick='makeInactive($idMaker)'>Pause this</button>
</li>";
$errorMessages[] = $error_ListActives;
$rowCount++;
}
Why not:
<button onClick="makeInactive(<?php echo $row['id'] ?>);">...</button>
embed the ID code as a parameter to your MakeInactive() call. Other alternatives are to simply use some DOM, e.g.
<li id="xxx"><button onclick="makeInactive(this);">...</button></li>
<script>
function makeInactive(el) {
el.getParent('li').disable(); // not real code, but shows the basic idea
}
</script>
First of all, you're creating the same exact function multiple times on your page. Your other buttons don't know which makeInactive() function to use. Why don't you give all of your buttons the same class, and then create ONE function that is included on the page that fires when the buttons are clicked.
No offense, but this is kind of bad markup here.
I want to:
Read in text line from "textfile.txt".
'echo' that line to the page in a <div> element.
Read in a text line from "namefile.txt".
Make this line become some sort of pop-up-text for that <div> element.
My script:
<? PHP
$fhtext = fopen("textfile.txt","a+") or exit("Error 1");
$fhname = fopen("namefile.txt","a+") or exit("Error 2");
while(!feof($fhtext))
{
echo "<div title="HERE IS WHERE I AM STUCK">".fgets($fhtext)."<div/><br />";
}
Could I perhaps go:
echo "<div title="<? fgets($fhname) ?>".fgets($fhtext)."<div/><br />";
?
<?php
$fhtext = fopen("textfile.txt","a+") or exit("Error 1");
$fhname = fopen("namefile.txt","a+") or exit("Error 2");
while(!feof($fhtext) && !feof($fhname))
{
echo "<div title=\"", fgets($fhname), "\">", fgets($fhtext), "<div/><br />";
}
?>
I haven't used PHP in a long time, but this should work:
echo "<div title='" . fgets($fhname) ."'>" .fgets($fhtext). "<div/><br />";
Regarding:
Make this line become some sort of pop-up-text for that '' element.
If you mean 'popup' text, as in tooltips of the type you get when you hover over links/images, this is only available on some elements when their title attribute has been set, not DIVs.
As such you can either change the DIV to a A (link) element. Or use Javascript to detect a hover over the DIV and display a popup.
If you are sure both files have the same number of lines you could use the „file“-function of PHP. This will read the file into an array and you can loop over it with a for-loop:
<?php
$file1 = file('file1');
$file2 = file('file2');
for ($i = 0, $max = count($file1); $i < $max; $i++) {
echo $file1[$i].' '.$file2[$i];
}
Before you dump your fgets() data to the browser, you really ought to HTML encode it first. That will prevent accidental (or not so accidental) problems caused by HTML fragments that might be in your text files, or if the file name can be entered by the user (either as part of the URL or as part of a form).
As a rule of thumb, always HTML encode anything coming from a data source you don't control before spitting it out to the browser. That includes form fields, etc.
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? Basically, as I've already got the jquery, I just need to know how to show only the first X results in one div, then the rest in a seperate div.
My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.
Many thanks in advance. S
Thought I'd add the code I'm using below
$query = "SELECT * FROM ispress WHERE active = '1' ORDER BY YEAR(date) DESC, MONTH(date) DESC LIMIT 0, 7";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['date'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$bFirstTime = true;
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
echo '<div class="date">' . $timePeriod . '</div>' . PHP_EOL;
echo '<ul class="press">' . PHP_EOL;
foreach ($newsItems as $item)
{
if ($bFirstTime) {
echo '<li>';
echo '<img src="'.$wwwUrl.'images/news/'.$item['image'].'" width="'.$item['imgWidth'].'" height="'.$item['imgHeight'].'" title="'.$item['title'].'" alt="'.$item['title'].'" />
<h3>'.$item["title"].'</h3>
<p>'.substr($item['descrip'],0,244).'...</p>
<p>Read more</p>
';
echo '</li>' . PHP_EOL;
$bFirstTime = false;
} else {
echo '<li>';
echo '<img src="'.$wwwUrl.'images/news/'.$item['image'].'" width="'.$item['tnWidth'].'" height="'.$item['tnHeight'].'" title="'.$item['title'].'" alt="'.$item['title'].'" />
<h3>'.$item["title"].'</h3>
<p>'.substr($item['descrip'],0,100).'...</p>
<p>Read more</p>
';
echo '<div class="clear"></div>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
}
echo '</ul>' . PHP_EOL;
}
echo '<p>Older posts...</p>'. PHP_EOL;
echo '<div id="slickbox">This is the box that will be shown and display the rest of the news results. :)</div>'. PHP_EOL;
}
else
{
echo 'We currently have no press releases available';
}
This will hide the first 10 children. How are you planning on showing the other results? Buttons, fields, jqueryui widgets?
You will just need to add a click event which calls this function.
function limit_results(start, end) {
$('#things > .thing').each(index) {
if(index < end && index >= start) {
$(this).hide();
}
}
}
limit_results(1,10);
If you have your elements in a jQuery object already (say, $('#sql-results') holds all of your results), you can always do this: $('#sql-results:lt(10)') to work with the first ten elements, and $('#sql-results:gt(9)') to work with the rest of the elements.
You have to decide yourself how efficient your approach is for this amount of data you're processing.
Right, so for your specific markup structure, you can add this to your JS:
// Obviously this is untested and probably not bug-/typo-free
(
function($) {
var $slickbox = $('#slickbox').hide();
$('<ul></ul>')
.appendTo($slickbox)
.append('ul.press li:gt(9)');
$('#slick-toggle')
.bind(
'click',
function(){
$slickbox.toggle();
}
);
}
)(jQuery);
This would involve a lot of rewriting but jquery has a datatables plugin that will display the data. To use it you need to do something like
echo '<table id="news-table">'
echo '<thead>';//Datatables needs a thead with the correct number of columns. However you don't need to fill them in.
echo '<th>Date</th>';
echo '<th>Time Period</th>'
echo '</thead><tbody>';
while ($data = my_sql_fetch_array($result)) {
echo '<td>Whatever</td>';
echo '<td>Another Field</td>';
}
echo '</tbody></table>';
The jquery is then
$('#news-table').dataTable();
I'm not sure how it would do custom no data messages and I know that with the code you have written this may not be any good to you right now but I'm posting it because it could be useful for somebody looking for pagination info or for you if you want to do something similar again. Datatables is also useful because the user can choose the number of results they want to show, what column they want to sort by and what direction to sort in.
in your query
limit 0,10
for the rest
limit 11,xxx
When you print out each row's data count each iteration by incrementing a counter. When you get to 11 start a new div that has a different id to that of your 1st div that you already defined an id for. Now using jQuery you can hide and show the 2nd div with the remaining results as you please.
Divide the return values in your php file with a character
ex:
echo "this is first value +";
echo "this is second value +";
echo "this is third value +";
use javascript to separate the return values
ex:
var ajaxArray = ajaxValues.split("+");
now all three values are placed in ajaxArray and you may use anyone you want
ex:
ajaxArray[0] = this is first value