php Javascript variable quoting error - javascript

I'm having trouble with quotes in a line of the attached code.
It is part of a picture viewer. Picture data url "PicNotes" is read from mysql. I am attempting to enhance the result by adding a picture info pop-up but can't get the quotes right.
I have added some rem statements around 3 versions (attempts) to get it working.
$data = mysql_query("SELECT * FROM $tbl_name WHERE type='$type' LIMIT $start, $limit_col_1");}
// Your while loop here
while($row = mysql_fetch_array($data))
{//REM If there is no info don't show the info link
if ($row[PicNotes]) {
// $icon= <img src='images/info.png'>; //REM This line was the original call for the pop-up script
// $icon = "<a href=notes/tempest_series.php><img src=images/info.png></a>"; //REM This line works but does not have any of the Jarvascript or URL variable from the DB
// $icon = "<a href=notes/$row[PicNotes]><img src=images/info.png></a>"; //REM This line doesn't crash but the URL is corrupted
$icon = "<img src=images/info.png>"; //REM This line crashes with an "Unexpected T_STRING error
}else{
$icon='';}
// Display LHS Thumbnail and Viewer Pic Data
echo "<a href='images/".$row['vfile']."' rel='enlargeimage::mouseover' rev='loadarea' title='<b>".$row['Title']."</b><br />".$row['Medium']." ".$row['iw']." x ".$row['ih']." cm. $icon'><img border='1' src='images/".$row['tnfile']."
' alt='' width='".$row['tnx']."' height='".$row['tny']."' class='tn' /></a><br />";
}
Please can somebody put me on the right track.

1) Escape the inner quotes:
$icon = "<img src=images/info.png>";
2) Use single quotes:
$icon = "<a href='JavaScript:Popup(notes/$row[PicNotes])'><img src=images/info.png></a>";

Use curly braces ({}) for better variable concatenation
$icon="<img src=\"images/info.png\">";

Related

Quotes breakes JS variable

I need create var in js script, something like this:
var map = "<div class="map"><?php echo do_shortcode('[wpgmza id="3"]'); ?></div>";
but apostrophes and quotes breaks code. How to change it to make it works?
Use other quotes or escape them.
var map = `<div class="map"><?php echo do_shortcode('[wpgmza id="3"]'); ?></div>`;
var map2 = "<div class=\"map\"><?php echo do_shortcode('[wpgmza id=\"3\"]'); ?></div>";
console.log(map);
console.log(map2);
Escape the quotes.
var map = "<div class=\"map\"><?php echo do_shortcode('[wpgmza id=\"3\"]'); ?></div>";
If you open the value with " then JavaScript will look for the second " to know where the value ends. As you're now using this within the value as well it stops to early. By escaping the " that you want to use within your value, you will make sure JavaScript knows it is part of the value.
So in your code, Javascript will stop after the second ":
var map = "<div class="
As you can see you did now open it with " and after the = there is another " so the value will be closed. How ever, you still have some more code after it: map"><?php echo do_shortcode('[wpgmza id=\"3\"]'); ?></div>";
As JavaScript doesn't know what to do with this part, it'll throw an error.
Maybe this will explain it better if you don't understand the above part:
You can see it as an if statement where if { } you need two brackets. One to open { and one to close }. In your value you need also two characters, one to open and one to close. In your case you use a " to open the value and " to close. So as soon as it hits the second " it'll close the value.
The assignment you did is comparable with this if-statement: if { } }. JavaScript doesn't know what to do with the latest }, as there is no other if-statement to close and because of that reason it'll throw an error.
You can fix the value of your variable using a few methods:
Escaping the quotes
You can add a backslash to the double quotes to make the JS parser ignore them. I would also concatenate the PHP value for clarity:
var map = "<div class=\"map\">" + <?php echo do_shortcode('[wpgmza id="3"]'); ?> + "</div>";
Using single quotes and double quotes alternatively
If you need to use double quotes in the value, you can just wrap it with single quotes.
var map = '<div class="map">' + <?php echo do_shortcode('[wpgmza id="3"]'); ?> + '</div>';
It also works the other way around, if you prefer single quotes in HTML attribute values
var map = "<div class='map'>" + <?php echo do_shortcode('[wpgmza id="3"]'); ?> + "</div>";
Template literals
In ES6, you can use template literals using the back-tick character. Notice you can both use single and double quotes inside a template literal:
var map = `<div class="map"><?php echo do_shortcode('[wpgmza id="3"]'); ?></div>`;
var map = /"<div class=/"map/"><?php echo do_shortcode('[wpgmza id=/"3/"]'); ?></div>/";
or
var map = "<div class='map'><?php echo do_shortcode('[wpgmza id='3']'); ?></div>";

Use file_get_contents() and implode() to pass array to javascript not working

I am developing a simple image gallery which shows images and related caption.
All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.
[...]
for($x = 2; $x < $lenght; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x];
}
for($x = 2; $x < $lenght; $x++) {
$filename = $capdirectory."/".$lsc[$x];
$filesc[$x] = file_get_contents($filename);
}
//Create array for JS
$captions = '["' . implode('", "', $filesc). '"]';
$images = '["' . implode('", "', $filesi). '"]';
?>
<script>
var captions = <?php echo $captions; ?>;
var images = <?php echo $images; ?>;
[...]
Images work properly and I can also print caption's file name instead of caption
i.e.
$filesc[$x] = $filename;
but when I use "file_get_contents()" to read file the gallery stops working.
If I echo $captions and manually set $captions with the very same output
e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, so the array should be properly formatted...
Thank you in advance
SOLUTION
I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.
for($x = 0; $x < $lenght-2; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x+2];
}
In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!
var images = <?php echo json_encode($filesi); ?>;
In JS you have to escape new lines in strings like this:
var multilineString = "this is\
just an example";
Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().
UPDATE
Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item';?

Recognising strings between certain tags in external file -PHP

I am new to php, and want a script that can recognise text between certain tags in an external file.
I managed to find an answer here, that recognises the text in tags in a set string, but I am unsure of how to get the file to recognise the tags in an external text file.
PHP:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "The <tag>Output</tag>"; // this is the string
$parsed = innerh($fullstring, "<tag>", "</tag>");
echo $parsed;
?>
External File:
<tag>This text</tag> <!-- This is the target -->
Similar to what you are already doing. Currently you are making a string with that tag and when you want to read it from a file you can simply do
$fullstring = file_get_contents('your-file.html');
No other changes are required. You might need to provide full path of that file but that's about it.
That function reads a file and returns its contents in a string which you can save in your variable just like you built the variable manually.
Your code must be somthing like this:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
// Open a file with READ-ONLY flag ("r") and start of begining for read.
// See: http://php.net/manual/en/function.fopen.php
$fp = fopen("/path/to/file", "r");
// Check that file is opened and ready for read
if ($fp) {
// Until we have content on file, we resume reading
while (!feof($fp)) {
// Read from file, line by line.
// See: http://php.net/manual/en/function.fgets.php
$line = fgets($fp);
// Process line by line and print result
$parsed = innerh($line, "<tag>", "</tag>");
echo $parsed;
/* If your input file is a file without a new line or something like it,
just add a `$line = '';` before while line and change read line with
`$line .= fgets($fp);`, also remove process line and print line. After
that your file is on $line variable ;). */
}
}
?>

DomDocument -> outputting changed html

below is my current code that pulls the html
BEFORE
<td class="winner betting-movement">
11/8<img src="/images/site/blue-arrow-small.gif" width="6" height="11">6/4 </td>
Then replaces images with text
After
<html><body><td class="winner betting-movement">$movement = $article->childNodes->item(12)->ownerDocument->saveHTML($article->childNodes->item(12))."<br />";
<? php #$dom3->loadHTML($movement);
$xpath5 = new DOMXPath($dom3);
foreach($xpath5->query('//img[contains(#src, "blue")]') as $link) {
$link->parentNode->replaceChild($dom3->createTextNode(" > "), $link);
}
foreach($xpath5->query('//img[contains(#src, "red")]') as $link) {
$link->parentNode->replaceChild($dom3->createTextNode(" < "), $link);
}
echo $dom3->saveHTML();?>
works great but all i need to do now is output the new saved html as just the inner text e.g "11/8 > 6/4"
echo $dom3->saveHTML()->textContent;
sadly the last line doesn't work and im reaching out to see if anyone could point me in a quick fix for this?
Can you do echo htmlentities($dom3->saveHTML()); - this would encode the HTML to be viewable to the user. More info: http://php.net/manual/en/function.htmlentities.php

Javascript Error "Null is not an Object" with a dynamically created html table

I have a dynanamically created html table with a picture in the last cell of each row (like.png). What I would like to achieve is after the user has clicked on this picture another one is diplayed (like1.png). However I keep getting "Null is not an Object", there is maybe something wrong with my javascript code ...
Thank you for your help :)
Here is my php that creates the table :
<?php
$pictureid = 1;
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo '<tr>';
echo'<td>'. ucfirst($results['song_name']).'</td>';
echo'<td>'. ucfirst($results['song_artist']).'</td>';
//echo'<td>'. ucfirst($results['song_album']).'</td>';
echo '<td>';
echo '<img src="images/like.png" id="artist'.$pictureid.'" onClick="action(artist'.$pictureid.')"/></a>';
echo '</td>';
echo '</tr>';
$pictureid = $pictureid + 1;
}
And here is my javascript :
<script language="javascript">
function action(imageid)
{
if(document.getElementById(imageid).src == 'like.png' )
document.getElementById(imageid).src = 'like1.png';
else
document.getElementById(imageid).src = 'like1.png';
}
</script>
You're missing some quotes here:
echo '<img ... onClick="action(\'artist'.$pictureid.'\')"/></a>';
// quotes missing here ----------^---------------------^
In your output HTML it should currently look like, e.g., this:
<img ... onClick="action(artist1)"/>
This would call the method action() and use a variable of the name artist1, which does not exists. So in your method document.getElementById() returns null and you get the error.
Your method, however, requires a string input and thus you should enclose the parameter with quotes, so that it generates output like this:
<img ... onClick="action('artist1')"/>

Categories

Resources