Quotes breakes JS variable - javascript

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

Related

Google Sheet webapp: Display a button programmatically

I am trying to display a button under certain condition on my HTML output
I succesfully wrote the code like this:
<?
var HTMLToDisplay = "";
if (data[i][5] == 0) {
HTMLToDisplay = ""
} else {
HTMLToDisplay = '<input type="button" value="Réserver" onclick="openForm(' + "'" + new Date(data[i][4]).toLocaleDateString('fr-BE', options) + "'" + ",'" + data[i][3] + "'," + data[i][0] + ')" />'
}
?>
<?= HTMLToDisplay ?>
But unfortunately, the HTML code appears in plain text rather than in the code
In fact the script automatically added some unwanted double quotes
Any idea how I can display my button just by code, without doing complex stuff?
Thanks a lot
In your script, please modify as follows and test it again.
From:
<?= HTMLToDisplay ?>
To:
<?!= HTMLToDisplay ?>
By this, if the value of HTMLToDisplay is the valid HTML tag, the value of HTMLToDisplay put as the raw string. When it is loaded by the browser, it is shown as a button. If no button is shown, please check the value of HTMLToDisplay again.
Reference:
Force-printing scriptlets

syntaxerror: expected expression, got '}' in php and javascript

I have a select option and when I select an option it must show my colors
Look at my codes
<?php foreach ($colors as $color) { ?>
<option onclick=addColor("<?php echo $color->title ?>", this) value="<?= $color->id ?>"><?= $color->title ?></option>
<?php } ?>
script
function addColor(color_name, tag) {
var optionTag = $(tag);
var selectColor = '<span class="select-color mr-1"><img src="public/images/dialog_close.png">+color_name+</span>';
var divRow = optionTag.parents('.row');
divRow.append(selectColor);
}
but i get this error.
SyntaxError: expected expression, got '}'
Try
PHP
You are not defining the end and beginning of your onclick attribute, enclose it with " " as you also need a string parameter to your method enclose it with ' ' as to not terminate the attribute string prematurely.
<option onclick="addColor('<?php echo $color->title ?>', this)" value="<?= $color->id ?>"><?= $color->title ?></option>
Javascript
Terminate your string around the variable to indicate that the variable is to be appended to the string. If you just write + var + inside a string that will be a normal part of the string.
var selectColor = '<span class="select-color mr-1"><img src="public/images/dialog_close.png">'+color_name+'</span>';
You are also mixing output methods in your PHP, I would recommend sticking to one kind of make it easier to read your code.

How do I get a php element into a javascript

I am scripting a chat for a forum, and it seems that it uses php to get the user's avatars. (PS idk anything about weather or not javascript can use sql databases or how to work with it so i would like to stick to php) But the problem is that the javascript isnt liking it if i put php variables into it.
getUserNodeString: function(userID, userName, userRole) {
var encodedUserName, str;
if(this.userNodeString && userID === this.userID) {
return this.userNodeString;
} else {
encodedUserName = this.scriptLinkEncode(userName);
str = '<div id="'
+ this.getUserDocumentID(userID)
+ '"><a href="javascript:ajaxChat.toggleUserMenu(\''
+ this.getUserMenuDocumentID(userID)
+ '\', \''
+ encodedUserName
+ '\', '
+ userID
+ ');" class="'
+ this.getRoleClass(userRole)
+ '" title="'
+ this.lang['toggleUserMenu'].replace(/%s/, userName)
+ '">'
+ userName
+ '</a><?php echo \'<img src="test.php" />\' ?>'
+ '<ul class="userMenu" id="'
+ this.getUserMenuDocumentID(userID)
+ '"'
+ ((userID === this.userID) ?
'>'+this.getUserNodeStringItems(encodedUserName, userID, false) :
' style="display:none;">')
+ '</ul>'
+'</div>';
if(userID === this.userID) {
this.userNodeString = str;
}
return str;
}
},
'</a><?php echo \'<img src="test.png" />\' ?>'
is the line thet im trying to use, i havent put my variable yet, im trying it with a test immage first
It should be like this:
+ '</a><img src="<?php echo htmlentities($src, ENT_DISALLOWED | ENT_QUOTES | ENT_HTML5) ?>" />'
You should only escape back into PHP for the specific part of the code that needs to contain the PHP variable. The rest of it should be literal HTML or Javascript.
You should also use htmlspecialchars() to ensure that the variable content is encoded properly to be used in an HTML attribute, in case it contains special characters.
The above is for getting a PHP variable into a JS literal that contains HTML code. If just you want to get a PHP value into a Javascript variable, it's slightly different. Then you can use json_encode() to generate the JS representation:
var js_var = <?php echo json_encode($php_var) ?>;
UPDATE
this is a .js file, its taken from ajax chat
It won't work inside a .js file, because those files are not parsed by PHP. It can be set up so that they get parsed, but I strongly suggest you don't do it, ever.
Besides, you don't need PHP for what you're doing.
ORIGINAL ANSWER
This is not a proper PHP inside this line:
+ '</a><?php echo \'<img src="test.php" />\' ?>'
Or just to strip the PHP part:
<?php echo \'<img src="test.php" />\' ?>
To get it to work, you need to remove those escaped quotes (you don't need to worry about JS quotes, because PHP parser will hit the file first, leaving you with whatever you echoed), and add a semi-colon:
<?php echo '<img src="test.php" />'; ?>
and the full line should be:
+ '</a><?php echo '<img src="test.php" />'; ?>'
which will render as:
+ '</a><img src="test.php" />'
It doesn't really make sense to use PHP for this, but okay.
Of course, it has to be inside a file that the server will parse with PHP (.php files by default, strongly suggest you don't set up PHP parsing for JS files). You never answer about the filetype in the comments.

php Javascript variable quoting error

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\">";

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