Google Sheet webapp: Display a button programmatically - javascript

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

Related

Problems with PHP variables in the URL of a JavaScript function

I'm using the following script to use a popup window to load a $_GET address:
while ($row1 = $sth1->fetch(PDO::FETCH_ASSOC)){
if($_SESSION['scontact_id'] == 'scontact_id' && $row1['shared_id'] != '' && $row1['shared_id'] != '0'){
echo "<td> <center><button onclick='myFunction()'><img border='0' alt='Contacts' src='/Welcome/modules/mod_crmsearch/images/peoplesmall.png'></button></center>
<script>
function myFunction(shared_id) {
window.open('". $mywebsite . "vcontact_id=" . $row1['shared_id'] ."' +shared_id, '_blank', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script> </td>";
However, it only loads the first row in the loop correctly. After that, it displays the same $_GET address, regardless of where it is in the while loop. It does the same thing if I convert the row to a php variable and pass the PHP variable, to the script, as a JavaScript variable. It works fine, without the popup, like this:
echo "<td>"."<a href='" . $mywebsite . "vcontact_id=" . $row1['shared_id'] . "' target='_blank', '_blank', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400'><center><img border='0' alt='Contacts' src='/Welcome/modules/mod_crmsearch/images/peoplesmall.png'></center></a>" . "</td>";
I'm not very familiar with JavaScript. Any help would be greatly appreciated.
Chage this part:
echo "<td> <center><button onclick='myFunction()'>
for this:
echo "<td> <center><button onclick='myFunction(\"" . $row1['shared_id'] . "\")'>
EDIT: Or make it one line instead of using a function:
echo "<td> <center><button onclick='window.open(\"". $mywebsite . "vcontact_id=" . $row1['shared_id'] ."\", \"_blank\", \"toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400\");'><img border='0' alt='Contacts' src='/Welcome/modules/mod_crmsearch/images/peoplesmall.png'></button></center></td>";
myFunction is being overwritten each time in the loop. You could always rewrite the code with an increment counter to change the function name. It's typically better to not mix javascript in php in my opinion. You could always just pass these in as additional parameters into your function where you are outputting php / js.
You are continuously redefining the function: myFunction(). you should output the script tag once, outside the loop, and change the onclick attribute on your button to ...<button onclick='myFunction(" . $row1['shared_id'] . ")'>..., if I am reading your problem correctly
Please try below code:
<?php
while ($row1 = $sth1->fetch(PDO::FETCH_ASSOC)){
if($_SESSION['scontact_id'] == 'scontact_id' && $row1['shared_id'] != '' && $row1['shared_id'] != '0'){
echo "<td> <center><button onclick='myFunction(".$row1['shared_id'].")'><img border='0' alt='Contacts' src='/Welcome/modules/mod_crmsearch/images/peoplesmall.png'></button></center></td>";
}
}
?>
<script>
var mywebsite = "<?php echo $mywebsite ?>";
function myFunction(shared_id) {
window.open(mywebsite+"vcontact_id="+shared_id, '_blank', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
I believe you simply need to move your script outside the if loop, yet maintain it in the while loop and you need to add your (shared_id) that is required by the function, to the click event.
<?php
while ($row1 = $sth1->fetch(PDO::FETCH_ASSOC)){
if($_SESSION['scontact_id'] == 'scontact_id' && $row1['shared_id'] != '' && $row1['shared_id'] != '0'){
echo "<td> <center><button onclick='myFunction(".$row1['shared_id'].")'><img border='0' alt='Contacts' src='/Welcome/modules/mod_crmsearch/images/peoplesmall.png'></button></center></td>";
}
echo "
<script>
function myFunction(shared_id) {
window.open('". $mywebsite . "vcontact_id=" . $row1['shared_id'] ."' +shared_id, '_blank', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
";
}
If you care at all about page optimization, it would be far wiser instead of looping the script in the while statement, to set a data variable and a class on the button and use an onclick event to determine the values so you don't have 20 instances of the same script with different values on the page.
For example:
Inside your button:
class='clicked' data-id='".$row1['shared_id']."'
Then use jquery for the script
<script>
$( ".clicked" ).click(function() {
var data = $(this).attr('data-id');
window.open('". $mywebsite . "vcontact_id='+data', '_blank', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>
This looks for a click event on the class "clicked" which we assigned to the button. When button is clicked, we get the value of "data-id" and set it as a variable "data". We then call that variable instead of echoing a php variable. This allows us to take the script out of the loop and not write it to the page multiple times.

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.

Dynamically Adding Content to Text Fields Using Javascript

So here is my problem. I have the below set of javascript code and HTML.
What is supposed to happen is that as you click on various checkboxes in a form, the script is supposed to take the Value of the Checkbox you checked and fill in a text field below that has a similar "name" identifier. The below code works for all values but one. The one with a space in the value "Character Only" doesn't work. I tried to use the Javascript method .Replace(" ", "-") to accomplish replacing the space with a hyphen but it doesn't seem to work. Since the HTML is being dynamically created via a PHP loop, I can't just add in the needed values and hard code everything.
Is there a way to make
JSFiddle - The full program and HTML layout.
The Javascript (Click the JSFiddle link to see the entire result)
function autofill(ElementName) {
//window.alert('You got this: ' + ElementName);
if(document.getElementById('keyword-' + ElementName.toLowerCase()).checked == true) {
document.getElementById('keyword-entry-' + ElementName.toLowerCase()).value = document.getElementById('keyword-' + ElementName.toLowerCase()).value;
} else {
document.getElementById('keyword-entry-' + ElementName.toLowerCase()).value = '';
}
}
// window.alert('This value is: ' + document.getElementById('keyword-ally').value.toLowerCase() );
//--> </script>
The PHP being used to create the HTML elements for the above JScript
<?php
$keywords = array("Ally" , "Breaker" , "Character Only" , "Combo" , "Desperation" , "Item" , "Kick" , "Multiple" , "Powerful" , "Punch" , "Ranged" , "Reversal" , "Stance" , "Stun" , "Taunt" , "Terrain" , "Throw" , "Unique" , "Weapon");
$i =0;
foreach($keywords as $keyword_name) {
echo '<td style="width: 20%;">' . zen_draw_checkbox_field('ufs_keywords[]', $keyword_name, in_array($keyword_name, $pInfo->resources), '', 'id="keyword-' . str_replace(" ","-",strtolower($keyword_name)) . '"') . ' <label for="keyword-' . str_replace(" ","-",strtolower($keyword_name)) .'">' . $keyword_name . "</label><br />" . zen_draw_input_field('ufs_keywords_entry[]', '', 'id="keyword-entry-' . str_replace(" ","_",strtolower($keyword_name)) . '" style="width:100px; float: right;"') . "</td>" . "\n\n";
$i++;
echo ($i % 5 == 0 ? "</tr>\n\n<tr>" : "");
}
?>

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')"/>

Google Maps API - storing image URL and calling it

I've added an image URL to an entry in the mySQL database, and I want it do be displayed in the information window on my sidebar.
Here's what the part I'm fiddling around with:
downloadUrl("genxml.php", function(data) {
var xml = data.responseXML;
var locations = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < locations.length; i++) {
var name = locations[i].getAttribute("name");
var address = locations[i].getAttribute("address");
var type = locations[i].getAttribute("type");
var price = locations[i].getAttribute("price");
var img = locations[i].getAttribute("img");
var point = new google.maps.LatLng(
parseFloat(locations[i].getAttribute("lat")),
parseFloat(locations[i].getAttribute("lng")));
var html = "<div class=loc-img><img src=" + img + "/></div><div class=loc-name>" + name + "</div> <br/>" + address + "<br/>" + "<div class=loc-type>" + type + "</div><div id=loc-price>Price Rating:" + price + "</div>";
The bit at the bottom looks right to me, so I can't work out what's wrong.
The image is saved on the server, and the URL has been added to the img field of the entry, and there are no spelling errors. When the page loads, and the info window loads, this shows in the Inspector.
<img src="null/">
Here are the details of the column from phpMyAdmin, whcih I think could be causing the problem. varchar(120) latin1_swedish_ci, Null is set to no. I assumed that because it was a URL, varchar would be the appropriate choice.
Any thoughts?
EDIT: I am also having a similar issues with another field. I think it might be related. There's a 'price' field, set to int(5), and is simply a rating of 1 to 5. However, when the info window displays, it just says 'null'
I've actually managed to work out the problem.
Rather simple, yet easily overlooked!
When adding new fields to each item, you need to remember to register them in the XML converter that pulls the information from the database, and then converts it to a Maps-readable format (XML).
In my case, I had to go into genxml.php (as directed by the Maps documentation), and make it look like this:
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'price="' . $row['price'] . '" ';
echo 'img="' . $row['img'] . '" ';
echo '/>';
}
Hope that helps someone else!

Categories

Resources