Onclick event for a button - html

I am creating a simple onclick event for a button. It's just not working. Below is what I wrote.
<script type='text/javascript'>
rec(){
<?php
$myfilename = "info.txt";
if(file_exists($myfilename)){
echo file_get_contents($myfilename);
}
?>
};
</script>
<button onclick="rec()">Click me</button>
Not sure, what wrong. I also commented entire php and just tried to echo hi, that also didn't work.
Kindly request your advice. Thanks.

Try printing out your javascript rather than putting PHP inside your javascript. For example you can try.
<?php
$myfilename = "info.txt";
if(file_exists($myfilename)){
$file = file_get_contents($myfilename);
echo "<script type='text/javascript'> function rec(){ console.log($file); console.log('This is JS being printed by PHP'); }</script>";
}
?>
Please keep in mind you should declare your function with the function keyword and there is no way for us to tell what $myfilename returns without more information, but if you're just trying to print html inside of PHP this should work for you.

Related

How to insert HTML code into HTML file from a .gs using Google Apps Script

My variables I'm inserting into an HTML file using the code below inserts the variables as plaintext and does not register code within my variables.
function sendEmail(){
var htmlBody = HtmlService.createTemplateFromFile('emailFormat');
var variableOne = "text";
htmlBody.example = '<p>' + variableOne + '</p>';
var email_html = htmlBody.evaluate().getContent();
MailApp.sendEmail({
to: "email#email.com",
subject: "subject",
htmlBody: email_html
});
}
The code above makes anywhere I put <?= example ?> within the file 'emailFormat' become "<p>text</p>". The problem is it does not display it as "text" it displays "<p>text</p>" entirely. How do I get it to show register the <p>'s as code?
The tags <?= ?> will escape the output, thus <?= <p> ?> will "print" the string <p> and not a paragraph tag.
You can use <?!= ?> to not escape the output. Those are useful for including additional HTML and inline JavaScript, CSS files into your templates. Using the exclamation mark should fix your issue.
But in your case, try just putting the <p> tags outside <?= =?> tags like this:
<p><?= example ?></p>
That's the typical way to do it. Or if you need to switch the tags, you could use the <?!= option, but that puts HTML in your JavaScript... it's a subjective choice, but you can also control options by using the <? ?> tags like this:
Code.gs
// html refers to a template
html.type = "p";
html.content = "some paragraph content!";
template.html
<? if (type === "p") { ?>
<p> <?= content ?> </p>
<? } ?>
Try this:
function sendEmail(){
var v1="Hello World";
var html='<p>' + v1 + '</p>';
MailApp.sendEmail({to: "email#email.com", subject: "Email Test", htmlBody: html});
}
We don't really load html into html files from gs file scripts except possibly via the Google Apps Script Advanced API. We can however load html directly into the Document Object Model of a browser by using google.script.run and then it's just a matter of getting the element by id and loading it's text or innerHTML via Javascript. I don't think even scriplets actually load it into the html file but I'm not sure about that.

function is not defined at HTMLInputElement.onclick

I'm using this example to try and update a visualization I created. I'm literally using the same piece of code, and yet I keep getting an error that says Uncaught ReferenceError: liste is not defined at HTMLInputElement.onclick. I looked a bit around and tried various solutions, but none of them seemed to work. Here is a code snippet :
<div id="option">
<input
name="updateButton"
type="button"
value="50"
onclick="liste(50)"/>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js'></script>
<script src='script.js' charset='utf-8'></script>
And my function liste works perfectly fine, since when I launch it "by hand" from my script it does what it's supposed to do. Here is what it does :
function liste(seuil){
for (var i = 0; i < seuil; i++) {
dataSeuil[i] = data[i];
}
graphe(dataSeuil);
}
The graphe function is the plotting function.
Here is a screenshot of what happens when I click the button. I've tried putting my <script> </script> tags before the tag but it doesn't help.
Please make sure onclick function is outside of the ready handler . Please check the below link
jQuery onClick Function not working

Yii2 Abnormal behavior - update div via ajax call with a jui tab widget of a render ajax action

Good day folks,
I am having an issue with Yii2, dunno whats goin on after searching online haven't found an answer.
Updated Question with more details
Here is a summary I am trying to change div content of my view via an ajax call to a controller action – the controller action I am calling does nothing but renders another view file which contains a Jui Tab.
The problem is it loads the home page + my Content at a lower part not processed.
If I visit the URL of the action that the ajax request calls, it displays properly with no issues – When I try to append it to my div on another view, this problem occurs.
Here are screenshots of my view
Page Displaying correctly on visiting URL
https://www.dropbox.com/s/77ovpl6fnznjs1p/Page%20displaying%20correctly%20on%20visiting%20URL.png?dl=0
Updating div with the rendered view displays content in a wrong manner
https://www.dropbox.com/s/6nld4wk1p9pkhz9/Screenshot%20of%20the%20update%20view.png?dl=0
A- Initial View Code
Here is my first view code – Contains a div that you click to fireup the ajax call and another div called content which gets the response
brense.PHP
<?php
use yii\helpers\Html;
use yii\jui\Tabs;
?> <div style="background: blue; cursor: pointer; width:100px;" id="brense">Click ME</div><div id="content">Content</div>
B- Ajax (JS File) `$('#brense').click(function(){
alert('click Received');
$.ajax({
url:'index.php?r=assignments/get-me2',
Type:'GET',
success:function(data){
alert("bombo");
$('#content').append('<div>Appended Content</div>');
$('#content').html(data);
}
});
});
`
C- Controller Action – Called by Ajax
public function actionGetMe2(){
return $this->renderAjax('tab');
}
D- Tab’s View that should be loaded inside the div content
<?php
use yii\helpers\Html;
use yii\jui\Tabs;
?>
<div>
<?php echo Tabs::widget(
['items'=>[
['label'=>'One','content'=>'Content 1'],
['label'=>'Two ','content'=>'Content 2'],
],
]
);
?>
</div>
Ok, here is the problem. Yii and Yii2 have an automatic numbering of elements. It has elements that are called w0, w1, w2. In a normal page you have w0 1 time, Yii takes care of that. Because you bring in code with Ajax, the page is actually a new page, so it has it's own w0 element. if you take a look at the code that it has it calls
$('#w0').tabs();
Now that works fine when you look at the page alone, but it will not work ok at all on your page because after inserting the content on the page you have 2 w0 elements. It basically calls the tab on the first one of them (in my test it was the nav bar) and that messes it up. The solution is to give the tabs an id.
So your tab.php file should be:
<?php
use yii\helpers\Html;
use yii\jui\Tabs;
?>
<div>
<?php echo Tabs::widget(
[
'id' => 'tabs',
'items'=>[
['label'=>'One','content'=>'Content 1'],
['label'=>'Two ','content'=>'Content 2'],
],
]
);
?>
</div>
This should solve your problem, but you migth have other problems too. Like loading jquery and jquery ui 2 times, 1 with the main page the other with your ajax. Now STOP using renderAjax you should use renderPartial.
Your code should be: in the main view file:
<?php
use yii\jui\JuiAsset;
JuiAsset::register($this);
?>
<div style="background: blue; cursor: pointer; width:100px;" id="brense">Click ME</div><div id="content">Content</div>
<?php
$script = <<<EOD
$('#brense').click(function(){
alert('click Received');
$.ajax({
url:'index.php?r=site/get-me2',
Type:'GET',
dataType: 'html',
success:function(data){
$('#content').html(data);
$('#tabs').tabs();
}
});
});
EOD;
$this->registerJs($script);
I am registering jquerui ui asset at the top, if you already have it loaded it will not load it again. I have a function that brings over the ajax, and that function also calls $('#tabs').tabs(); to actually create the jquery ui tabs.
Your controller
public function actionGetMe2(){
return $this->renderPartial('tab');
}

Twig and CodeIgniter form rendering issue. Form is being displayed as a String and not the HTML form

My first time to use Twig template with CodeIgniter. I'm used to the default form functionality of the framework, but I was asked to try to render the form using Twig. I find the template engine to be nice and confusing at the same time. So that means, my controller would be very fat with code. But the main issue here is to render the form using twig.
Below is what I used to do when I want to render a form. View: TableSample.php
<?php
echo form_open("", array("name"=>"form_reg", "method"=>"post", "id"=>"form_reg"));
echo form_input("type"=>"text", "name"=>"fname", "value"=>set_value("fname"));
echo form_input("type"=>"text", "name"=>"lname", "value"=>set_value("lname"));
echo form_input("type"=>"text", "name"=>"emailaddress", "value"=>set_value("emailaddress"));
echo form_input("type"=>"submit", "name"=>"submit", "value"=>"Submit");
echo form_close();
?>
Controller: register.php
public function register (){
$this->load->view("TableSample");
if($this->input->post("submit")) {
/** retrieve input details, pass them as array to model, then redirect if registration is successful**/
}
}
But since I have to use Twig, things have been a little bit different.
public function register () {
$detail["form_open"] = form_open("", array("name"=>"form_reg", "method"=>"post", "id"=>"form_reg"));
$detail["form_input_name"] = form_input("type"=>"text", "name"=>"fname");
$detail["form_input_lname"] = form_input("type"=>"text", "name"=>"lname");
$detail["form_input_eadd"] = form_input("type"=>"text", "name"=>"email");
$detail["form_input_submit"] = form_input("type"=>"submit", "name"=>"submit", "value"=>"Submit");
$detail["form_close"] = form_close();
//codes for saving here
//call twig view
$this->twig->display("tableSample.html.twig", $detail);
}
tableSample.html.twig would be like this:
<html>
<head></head>
<body>
{{ form_open }} //will display form as a **String** and not THE **HTML** like this:
<form method="post" name="form_reg" id="form_reg"></form>
{{ form_close }}
</body>
</html>
I know I'm missing something, please point me to the right way of rendering this. Thank You!
ok, I think I got it. raw made it possible. Twig Raw Filter

Auto-selecting an <option> via JQuery in a dynamically-loaded <select>

Based on cool StackOverflow code, I successfully created a series of dynamically-loaded <SELECT> drop-downs. However, when processing the form (e.g., if there's an error in the submitted information) I need to automatically select the appropriate <OPTION> in the dynamically loaded <SELECT> blocks. I tried a solution that works with static <SELECT> blocks, but it didn't work on my dynamically-loaded block. (I'm hiding/showing <SELECT> blocks as they are needed.) Here's the code:
<?php do things at the beginning of the page ?>
<script>
$(function() {
$('#container_A1').hide();
$"#category_A0").change(function() {
$("#category_A1").load("http://domain.com/loader/"+$("#category_A0").val());
$("#container_A1").show();
});
});
</script>
<?php create the HTML page... ?>
<script><?php
if( isset($_POST['category_A0']) && $_POST['category_A0'] != '' &&
isset($_POST['category_A1']) && $_POST['category_A1'] != ''){ ?>
$(function() {
$("#category_A1").load("http://domain.com/loader/"+$("#category_A0").val());
$("#container_A1").show();
$("#category_A1").val("<?php echo $_POST['category_A1']; ?>"); // NOT WORKING
});
<?php
}
?>
</script>
Everything works fine except the last JQuery line that tries to set the value of the category_A1 <SELECT> block to the option defined in $_POST['category_A1']. That doesn't work. Is the .load() function not complete when the subsequent .val() function is called?
Thanks!
.load is an asynchronous function. jQuery will continue on to the lines while .load is running, so the second $("#category_A1").val("<?php echo $_POST['category_A1']; ?>"); will always be overriden by the result of $("#category_A1").load("http://domain.com/loader/"+$("#category_A0").val());