.html() help dont know how to handle it - javascript

...
success: function (reqCode) {
if (reqCode['error_code'] == 1) {
//Generiere Tabelle
$(".done").html(
'<p class="bold center"><?php echo "Besucher ".$month_name[' + reqCode['month'] + ']." ".' + reqCode['year'] + '; ?></p>'
'<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>'
'<script>'
'chart = new RGraph.Line("cvs", ' + reqCode['data_string'] + ');'
'chart.Set("chart.tooltips", ' + reqCode['labels_string'] + ');'
'chart.Set("chart.tooltips.effect", "expand");'
'chart.Set("chart.background.grid.autofit", true);'
'chart.Set("chart.gutter.left", 35);'
'chart.Set("chart.gutter.right", 5);'
'chart.Set("chart.hmargin", 10);' +
'chart.Set("chart.tickmarks", "circle");'
'chart.Set("chart.labels", ' + $reqCode['labels_tooltip'] + ');'
'chart.Draw();'
'</script>'
);
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
}
I don't know why every new line needs its own '..'. Anyway it's not working. Looked into the API reference but found nothing useful :(
Edit: For my second question:
This is what JSON response:
$response['error_code'] = '1';
$response['data_string'] = "[" . join(", ", $data) . "]";
$response['labels_string'] = "['" . join("', '", $labels) . "']";
$response['labels_tooltip'] = "['" . join("', '", $data) . "']";
$response['month'] = $month_name[$month];
$response['year'] = $year;
echo json_encode($response);

There does seem to be something wrong with that <script> tag, but really? You don't need to insert that <script> tag. You're already running JavaScript; just do this:
success: function (reqCode) {
if (reqCode['error_code'] == 1) {
var month_name = <?php echo json_encode($month_name); ?>;
//Generiere Tabelle
$(".done").html(
'<p class="bold center">Besucher ' + month_name[reqCode['month']] + ' ' + reqCode['year'] + '</p>'+
'<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>'
);
var chart = new RGraph.Line("cvs", reqCode['data_string']);
chart.Set("chart.tooltips", reqCode['labels_string']);
chart.Set("chart.tooltips.effect", "expand");
chart.Set("chart.background.grid.autofit", true);
chart.Set("chart.gutter.left", 35);
chart.Set("chart.gutter.right", 5);
chart.Set("chart.hmargin", 10);
chart.Set("chart.tickmarks", "circle");
chart.Set("chart.labels", reqCode['labels_tooltip']);
chart.Draw();
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
}
I've fixed some syntax errors in there, though I can't guarantee that there are none left. Just watch the JavaScript console for errors.

You should have a container element with class done on it, like:
<div class="done" />
In addition, you can short:
$('.done').html('..all the html..').fadeOut('slow').fadeIn('slow');
Moreover, as Vivin Paliath said, you should concat all the strings in the html using +
'<a>'+
'asdsad'+
'</a>'
Good Luck!

You need + signs
success: function (reqCode) {
if (reqCode['error_code'] == 1) {
//Generiere Tabelle
$(".done").html('<p class="bold center"></p>'+
'<canvas id="cvs" width="680" height="250">[No canvas support]'+
'<script>'+
'chart = new RGraph.Line("cvs", ' + reqCode['data_string'] + ');'+
'chart.Set("chart.tooltips", ' + reqCode['labels_string'] + ');'+
'chart.Set("chart.tooltips.effect", "expand");'+
'chart.Set("chart.background.grid.autofit", true);'+
'chart.Set("chart.gutter.left", 35);'+
'chart.Set("chart.gutter.right", 5);' +
'chart.Set("chart.hmargin", 10);' +
'chart.Set("chart.tickmarks", "circle");'+
'chart.Set("chart.labels", ' + $reqCode['labels_tooltip'] + ');'+
'chart.Draw();'+
''
);
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
}

You need to pass a single string to the html() function. Something like:
$(".done").html("<p>hello</p><p>goodbye</p>").
If you need to combine multiple strings you will need to use string concatenation, like:
var combinedString = '<p>hello</p>' + '<p>goodbye</p>'

Related

JQuery fails to load when i use a php variable

I'm incorporating PHP code into JQuery like this:
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
/* This is the line */var c = $c;
$('#data').load('data.php?v=' + count + '&c=' + c)
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
})</script>";
The PHP variable shows as blue, there are no errors showing, but when I run it it refuses to work. I've tested everything else and I'm 100% sure PHP is the one causing the problem.
How can I fix this?
If $c is your php variable you will need to quote and join it inside an echo tag.
But as Carton (+1) said, is it a string, integer, object?
If it's an integer, this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = " . $c . ";
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's a string this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = '" . $c . "';
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's an object, you will have to parse the var or encode it.
Sometimes if you want to echo or return big blocks of html inside php, you can use an output buffer to capture the html, and then you can either return the html via a function, or echo it. This just makes your html easier to read when it's not wrapped inside echo quotes tags.
<?php
// c sting php var
$c = 'string';
// start output buffer
ob_start();
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
let count = ($('.data').length + 25);
let c = '<?=$c?>';
$('#data').load('data.php');
$(this).on('click', '.btn-data', function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c);
});
});
</script>
<?php
// store everything between ob_start() and here into a php variable
$script = ob_get_clean();
// return script html
return $script;
// or echo script html
echo $script;
// not both together obviously
?>

Undefined variables in html templates for MailApp

I am trying to send an HTML email using MailApp.
This is the table where I will pull the data from:
After reading the documentations and posts on SO, I am still unable to pin point why the email sent out is showing undefined in the variables part.
Would appreciate if someone can point me to the right direction.
These are my codes:
sendHtmlEmail.gs
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = ss.getLastRow();
var quotaLeft = MailApp.getRemainingDailyQuota();
if((lastRow-1) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " email quota left and you're trying to send " + (lastRow-1) + " emails. Emails were not sent.")
} else {
for (var row = 2; row <= lastRow; row++){
var currentEmail = ss.getRange(row, 4).getValue();
var currentContact = ss.getRange(row, 3).getValue();
var currentNewSize = ss.getRange(row,8).getValue();
var currentSub = ss.getRange(row, 9).getValue();
var returnData = [currentContact, currentNewSize, currentSub];
var html = HtmlService.createTemplateFromFile('htmlTemplate');
html.data = returnData;
var template = html.evaluate().getContent();
var subjectLine = "Important notice";
MailApp.sendEmail({to: currentEmail, subject: subjectLine, htmlBody: template});
} //close for loop
Browser.msgBox("You have successfully sent " + (lastRow-1) + " emails.")
} //close else statement
}
htmlTemplate.html
<!DOCTYPE html><html><head><base target="_top"></head><body style="text-align: center;font-family: Arial;">
<div id="center" style="width:300px;border: 2px dotted grey;background:#ececec;margin:25px;margin-left:auto;
margin-right:auto;padding:15px;"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Simple_Alert.svg/600px-Simple_Alert.svg.png"
width="180" style="margin:10px 0px"><br /><div style=" border: 2px dotted grey;background:white;margin-right:auto; margin-left:auto;
padding:10px;"><h2>Alert</h2><h3>Important Notice <br /><br />
+ <?= data.currentContact ?> + '<br />' + <?= data.currentNewSize ?> + '<br />' + <?= data.currentSub ?> + '<br /></h3></div></body></html>'
I know that it is something to do with the htmlTemplate data.currentNewSize etc, but after tweaking my codes they are still showing undefined as shown in the image.
You are using an array in the method while the template is expecting an object.
Replace
var returnData = [currentContact, currentNewSize, currentSub];
with
var returnData = {currentContact: currentContact, currentNewSize: currentNewSize, currentSub: currentSub}
The issue lies in the html code. As I have declared the array in sendHtmlEmail.gs, I did not call it correctly in my htmlTemplate.html.
In this line:
var returnData = [currentContact, currentNewSize, currentSub];
currentContact is in position 0, currentNewSize is in position 1 and so forth.
In the htmlTemplate.html, I need to replace this line:
+ <?= data.currentContact ?> + '<br />' + <?= data.currentNewSize ?> + '<br />' + <?= data.currentSub ?> + '<br /></h3></div></body></html>'
with this:
+ <?= returnData[0];?> + '<br />' + <?= returnData[1];?> + '<br />' + <?= returnData[2];?> + '<br /></h3></div></body></html>'

How can I escape from PHP code inside Javascript?

var i = 1;
$("#add_row").click(function(){
var arr = "<tr><td><input type='hidden' name='counter' value='" + i + "'><input type='hidden' id='pd-id-" + i + "' name='pd-id-" + i + "'><input autocomplete='off' type='text' id='pd-search-" + i + "' class='hahaha'><ul style='width: 44.8vw' class='livesearch' id='pd-result-" + i + "' onclick='clickResult()'></ul></td><td><input type='text' required name='workdescription-" + i + "'></td><td><select></select></td><?php
$date = new DateTime();
$y=1;
if (date('d') < '18' AND date('d') > '2') {
for ($x = 1 ; $x <= 16 ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $x . "'></td>";
}
} else if (date('d') < '3') {
for ($x = 16 ; $x <= date('t', strtotime(date('Y-m')." -1 month")) ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $y . "'></td>";
$y++;
}
} else {
for ($x = 16 ; $x <= date('t') ; $x++) {
echo "<td><input type='text' name='hr-" . i . "-" . $y . "'></td>";
$y++;
}
}
$i++;
?></tr>"
;
i++;
$( "#tablebody" ).append(arr);
});
I need to escape the letter i inside the echo of the PHP. I want them to have the value of the javascript variable i at the top. How may I do this? Also is there a better way to do this?
Like I said in a comment above, there 's no need for PHP in this case. You can solve it with Javascript only. To answer your question correctly, here 's a possible solution with Javascript and PHP.
<table id="my-table">
<tr>
</tr>
</table>
<template id="my-template">
<td><input type="text" name=""></td>
</template>
<script>
var day = '<?= (new DateTime())->format('d') ?>',
daysOfMonth = '<?= (new DateTime())->format('t') ?>',
daysOfMonthOneMonthBefore = '<?= (new DateTime('-1 month'))->format('t') ?>',
template = document.getElementById('my-template'),
i = 1,
y = 1;
var positiveInt = new Number(day),
positiveIntOneMOnthBefore = new Number(daysOfMonthOneMonthBefore),
inputElement = template.content.querySelector('input');
if (positiveInt < 18 && positiveInt > 2) {
for (var x = 1; x <= 16; x++) {
inputElement.name = 'hr-' + i + '-' x;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
} else if (positiveInt < 3) {
for (var x = 16; x <= positiveIntOneMOnthBefore; x++) {
inputElement.name = 'hr-' + i + '-' + y;
y++;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
} else {
for (var x = 16; x <= positiveInt; x++) {
inputElement.name = 'hr-' + i + '-' + y;
y++;
var clone = document.importNode(template.content, true);
document.querySelector('#my-table tr').appendChild(clone);
}
}
</script>
As you said you need only the actual date from the server. The rest of the code is done with native javascript. You don t even need jQuery for this. This code example is not tested. This code uses HTML5 elements like the template tag. Make sure you are using the right HTML5 doctype. Beside that it should show you a possible way how to solve your issue.
Try your echos like this:
echo "<td><input type='text' name='hr-' + i + '-" . $x . "'></td>";
Remember that all the php code gets completely parsed server-side. Javascript is client side. Don't confuse javascript and php syntax. Concating with . is php, + is the javascript equivalent. Also use quotes consistently. E.g. " in php and ' in javascript. If you need " in Javascript, escape it like so: \".

Variable error in function called in InnerHTML

I am new to coding, and am facing an issue calling a function from innerhtml. I suspect the issue may be with the innerhtml syntax.
The problematic section is:
document.getElementById('arrowback').innerHTML = "<a href='#' onclick='return imtest(icount,imname);'><img src=/Images/ib/A2.png></a>";
If i change the the syntax to the below then it works for icount, which is a numeric value, not for imname:
document.getElementById('arrowback').innerHTML = "<a href='#' onclick='return imtest("+icount+");'><img src=/Images/ib/A2.png></a>";
I would like to call the imtest function with 2 variables through the innerhtml method. Below is the full code for reference:
<script type="text/javascript">
function clicker(buildname, imname, icount){
var displaybox=document.getElementById('displaybox');
if (displaybox.style.display === "none") {
alert(imname);
document.getElementById('imagebox').innerHTML = "<img src=" + imname + icount+".jpg height='400'>";
document.getElementById('arrowback').innerHTML = "<a href='#' onclick= 'return imtest(icount,imname);'><img src=/Images/ib/A2.png></a>";
document.getElementById('btitle').innerHTML = buildname;
} else {
document.getElementById('displaybox').style.display = "none";
}
return false;
}
function imtest(icount, imname) {
alert(icount);
}
</script>
You just need to add quotes around imname:
document.getElementById('imagebox').innerHTML = '<img src="' + imname + icount + '.jpg" height="400">';
document.getElementById('arrowback').innerHTML = '<img src="/Images/ib/A2.png">';
By the way, you forgot the quotes around both src attribute values, I've added them, and I've took the liberty of changing the quotes you use to have double quotes in your HTML.
See this codepen.
Working code...
Javascript
function imtest(icount, imname){
alert("icount:" + icount + "\n imname: " + imname);
}
function clicker(buildname,imname,icount){
var displaybox=document.getElementById('displaybox');
if(displaybox.style.display == "none"){
displaybox.style.display = "block";
document.getElementById('imagebox').innerHTML = "<img src='" + imname + icount+".jpg' height='400'>";
document.getElementById('arrowback').innerHTML = "<a onclick='return imtest(" + icount + "," + '"' + imname + '"' + ");'><img src='Images/ib/A2.png'></a>";
document.getElementById('btitle').innerHTML = buildname;
}else{
document.getElementById('displaybox').style.display = "none";
}
}
HTML
<div id="displaybox" style="display: none;">
<h1 id="btitle"></h1>
<div id="imagebox"></div>
<div id="arrowback"></div>
</div>
<button onclick="clicker('buildname', 'imname', 'icount');">Clicker</button>
In imtest function you are passing only one parameter and on onclick you are accepting two parameter.Check it
While accepting you shoulde write like this.
document.getElementById('arrowback').innerHTML = '<img src="/Images/ib/A2.png">';

To identify second mouse click on the same cell within the grid

i want to place an image inside the cell on the first click and another image on the second click at the same position. In order to do that i tried writing onclick function in the tag..but as its written within functions it wont work..is there any other way to achieve the need ? plz help?
JS for placing the images on click:-
function changeColor1(elem)
{
elem.innerHTML = '<img src="images/atom1.png" width="20px" height="20px" onclick=changecolor2(this) />';
//alert("Row Index is:"+elem.parentNode.rowIndex+elem.cellIndex);
var x= elem.cellIndex;
var y= elem.parentNode.rowIndex;
click_count(x,y);
}
function changeColor2(elem)
{
elem.innerHTML = '<img src="images/2circles.png" width="20px" height="20px" onclick=changecolor3(this) />';
//alert("Row Index is:"+elem.parentNode.rowIndex+elem.cellIndex);
var x= elem.cellIndex;
var y= elem.parentNode.rowIndex;
click_count(x,y);
}
code for making the grid:
$rows = 7; // define number of rows
$cols = 6;// define number of columns
echo "<center>";
echo "<table border='1' cellspacing=0 cellpadding='35' pixels'>";
for($tr=0;$tr<$rows;$tr++){
echo "<tr>";
for($td=0;$td<$cols;$td++){
echo "<td onclick=\"changeColor1(this)\" >&nbsp &nbsp</td>";
}
echo "</tr>";
Try this:
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function changeColor2(elem)
{
if(!hasClass(elem, 'clicked')){
//clicked first time
elem.className = elem.className + " clicked";//add clicked class to element on first click
elem.innerHTML = '<img src="images/2circles.png" width="20px" height="20px" onclick=changecolor3(this) />';
//alert("Row Index is:"+elem.parentNode.rowIndex+elem.cellIndex);
var x= elem.cellIndex;
var y= elem.parentNode.rowIndex;
click_count(x,y);}
else{
//clicked second time and onward
}
}

Categories

Resources