Generating Javascript variables using php - php

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";
}
?>

Related

PHP prints variable to screen and code stops running

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.

weird error of loading mysql data to javascript variable using php

I have accessed a database and fetched data (to make it simple, let's assume only one data), the data is an array and has one field 'link', which is a url.
I pass the value of $data['link'] to a php variable $l1; to compare, I also pass the actual url to another varibale $l2.
Then the next two lines try to pass the value to javascript variable. If I remove the first line (echo "var link1 = \"$l1\";";), it works; if I keep the first line, it doesn't (alert dialog not shown). I think it is the problem of the url, but the value of $l2 is exactly the same as $data['link'], the next two lines also appear the same in the source code of the html page.
Code is here:
<script type="text/javascript">
function readData() {
alert('haha1');
<?php
$l1 = $data['link'];
$l2 = "http://upload.wikimedia.org/wikipedia/commons/1/17/Affenpinscher.jpg";
echo "var link1 = \"$l1\";";
echo "var link2 = \"$l2\";";
?>
alert('haha2');
}
</script>
<body onload="readData();"></body>
Anyone have any idea why this happen? Thanks for helping!
I'm not sure whether I've understood your doubt. At any case, from intuition, I'd try out something like this:
<script type="text/javascript">
function readData() {
alert('haha1');
<?php
$l1 = json_encode($data['link']);
$l2 = "http://upload.wikimedia.org/wikipedia/commons/1/17/Affenpinscher.jpg";
echo "var link1 = ".$l1.";";
echo "var link2 = \"$l2\";";
?>
alert('haha2');
}
</script>
<body onload="readData();"></body>
Your URL might be "malformed" for javascript; and cause a parse error.
Let us know if this was the case...

<div title="Can I somehow put PHP code in this attribute?"></div> or is there another route I can take?

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.

Placing PHP within Javascript

I can't seem to get the PHP to echo out within a Javascript tag:
places.push(new google.maps.LatLng("<?php echo the_field('lat', 1878); ?>"));
What am I doing wrong?
Have you tried it without the quotes ?
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
PHP works when you execute the page, and it should work.
Please note that php does not execute when you run a JS function.
Please also make sure that you really have that the_field function.
I suspect you have your " quotes in the LatLng method arguments when there shouldn't be any.
Your php should output a string such as '50.123123123, 12.123144' (without the ' quotes). The LatLng method expects 2 values.
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
Try that.
If you're looking to populate a Google Map with markers as the result of a database query, you probably want to wrap it in a JSON web service. Something as simple as:
<?php
// file to query database and grab palces
// do database connection
$places = array();
$sql = "SELECT * FROM places";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$places[] = $row;
}
header('Content-Type: application/json');
echo json_encode($places);
exit;
And then in your JavaScript file:
// get places
$.getJSON('getplaces.php', function(response) {
for (var i = 0; i < response.length; i++) {
place[] = response[i];
places.push(new google.maps.LatLng(place.lat, place.lng));
}
});
If i understand what you are trying to do (maybe some more explanation of your problem is required for this), then this might be your answer:
places.push(new google.maps.LatLng(<?php echo '"' . the_field('lat', 1878) . '"' ?>));
EDIT: removed the ;

Get dynamically given div id's from document

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.

Categories