Make duplicate html document with autogenerated name - javascript

Essetially, I am building a very rudimentary website builder that uses forms on a page to manipulate the HTML of the page,displayed below the input boxes, which eventually the user can get the source of to put onto their own website. I have not built it yet, but I was thinking that I would need more than one template in case anyone was trying to edit the same template at the same time, and having their edits overridden by others using the program. Here is a mockup for your leisure:
Html Displayed below input:
<h1 class="heading">Hi guys!</hi>
Form mockup:
<input id="headingEdit">
<script>
document.getElementById("heading").innerHTML = document.getElementById("headingEdit").value;
</script>
My problem is one that may or may not be relevant, and that is that should someone want to edit this template, when someone else is also editing it, then surely the html would keep on getting overridden by each other, and no-one would get anywhere. What I therefore want to do is be able to, when a user clicks on the 'Edit this Template' button on the homepage, they are taken to a randomly generated page, which is an exact duplicate of a master page, make their edits, and then that page is deleted, or (when I add integration) stored in a users account.
This might be a duplicate question, but the answer has not come up in my research so far.
Thanks in advance.

you can use AngularJS
http://www.w3schools.com/angular/default.asp
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>

Here's a short PHP solution
$pageid = uniqid();
copy('template.html', $pageid . '.html');
print "Editable page is at: " .$pageid . ".html";
Add this somewhere in the template.html:
<?php
if (str_replace(' ', '', preg_replace('/\.html/', '', basename($_SERVER['PHP_SELF']))) !== 'template') {
print "<script>
var elems = document.getElementsByTagName('*'),
i;
for (i = 0; i < elems.length; i += 1) {
elems[i].setAttribute('contentEditable', 'true');
}
window.onbeforeunload = function(){
var a = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
a.onreadystatechange = function (b) {
if(a.readyState==4&&a.status==200){
}
}
xmlhttp.open('POST','remove_template.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send('id=" . str_replace(' ', '', preg_replace('/\.html/', '', basename($_SERVER['PHP_SELF']))) . "');
}
//Custom JavaScript goes here
</script>";
}
?>
Then remove_template.php is:
if ($_POST['id'] != 'template' && ctype_alnum($_POST['id'])) {
unset($_POST['id']);
}
You should obviously change what urls to your needs, also remove_template.php is kinda insecure. I haven't tested this yet. If you ever add a user system. Made the $pageid link to their user account. Then just pass an if to not add the window.onbreforeunload

If you can't support PHP you can use an icky JavaScript solution
window.editPage () { document.body.contentEditable='true'; document.designMode='on'; }
window.savePage () { localStorage.setItem('savedPage', document.body.innerHTML); }
window.getPage () { document.body.innerHTML = localStorage.getItem('savedPage'); }
Then you can add the function to the onclick attribute
<div onclick="window.editPage()">Edit Page</div>
I've found something called Surreal CMS (Content Management System) which might be what you want. Or maybe something like create.js

Related

White screen on form submit - google web app [duplicate]

At this stage I'm mostly used to backend Javascript and server side Java, so my HTML is not as savvy as it needs to be.
I've built several applications that require user input with Apps script, but I was using the now deprecated UI service, as I'm not a designer and this provided an easy way to design simple pages to pass data back and forth. With the UI service having been deprecated for some time, I'm begging the arduous task of migrating these services to the HTML service, and I'm noticing some difference in behavior.
For example, when submitting a form, the entire page refreshes to a blank page, and I can't seem to prevent that. The UI service would remain static for information re-entry, and I can't find a working method to get the HTML service to either stop refreshing or reload the form.
Simple code to reproduce my issue:
function doGet() {
return HtmlService.createHtmlOutputFromFile('test')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function logValues(value){
Logger.log('Something worked....');
}
With the index file being:
<form>
<input type="submit" value="Book Meeting" onclick="google.script.run
.logValues()">
</form>
Some things I've tried:
1) Adding a callback to the 'doGet' function, to attempt to get the page to load again.
2) Adding a whole new function to try and call a NEW HTML page.
The issue here is my poor understanding of the HTML service, but is there a simple way for me to just clear the form for re-submission, or alternatively just reload the page? None of the other questions I've found on SO adequately answer this question in a way I can understand.
Since you're technically submitting your form by clicking the submit button, then that creates the page refresh. You need to cancel the submit event with the preventDefault function, which "Cancels the event if it is cancelable, without stopping further propagation of the event."
See the docs here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
So maybe you can try something along these lines (straight from the docs):
function stopDefAction(evt) {
evt.preventDefault();
}
document.getElementById('my-checkbox').addEventListener('click', stopDefAction, false);
Another option is to remove the form/input elements and simply use a button element instead, which doesn't trigger a page refresh on click.
It's an interesting ride switching old UI services across, I just did that with one of my applications and it has really improved the readability of the code. I posted a copy of a basic version of what I was doing in another question
Once you get your head around it all it becomes a lot simpler. This is a really basic example of using multiple HTML files similar to your example using the HTMLService when submitting forms (you can pass in parameters instead)
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Main')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
}
function onLogin(form) {
if (form.username == "fuzzyjulz") {
var template = HtmlService.createTemplateFromFile('Response');
//Setup any variables that should be used in the page
template.firstName = "Fuzzy";
template.username = form.username;
return template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
.getContent();
} else {
throw "You could not be found in the database please try again.";
}
}
function include(filename) {
return HtmlService.createTemplateFromFile(filename)
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
Main.html
<?!= include('CSS'); ?>
<script>
function loadPage(htmlOut) {
var div = document.getElementById('content');
div.innerHTML = htmlOut;
document.getElementById('errors').innerHTML = "";
}
function onFailure(error) {
var errors = document.getElementById('errors');
errors.innerHTML = error.message;
}
</script>
<div id="errors"></div>
<div id="content">
<?!= include('Login'); ?>
</div>
CSS.html
<style>
p b {
width: 100px;
display: inline-block;
}
</style>
Login.html
<script>
function onLoginFailure(error) {
var loginBtn = document.getElementById('loginBtn');
loginBtn.disabled = false;
loginBtn.value = 'Login';
onFailure(error);
}
</script>
<div class="loginPanel">
<form>
<p>
<b>Username: </b>
<input type="text" name="username"/>
</p>
<input type="button" id="loginBtn" value="Login" onclick="this.disabled = true; this.value = 'Loading...';google.script.run
.withSuccessHandler(loadPage)
.withFailureHandler(onLoginFailure)
.onLogin(this.parentNode)"/>
</form>
</div>
Response.html
<div class="text">
Hi <?= firstName ?>,<br/>
Thanks for logging in as <?= username ?>
</div>

function variable not passing to global variable

Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);

How Display a div using jquery when user login?

I want to display my account only when user login into website and i am creating this into netsuite here is my account section html code
<div class="name" style="display:none;" id="
my_act">MY ACCOUNT</div>
I m using this script but its not working
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(function()
{
if (entityId != null && entityId != "")
{
$j('#my_act').css('display','block');
}
});
</script>
I would say try putting an alert in the if loop to check whether the element exists at the time when the script is run.
Possibly, the script is gettig executed prior to the element actually getting loaded in the DOM.
First of all, you can't properly manage logins with javascript/jQuery alone. Logins are best managed with a back-end language, like PHP or ASP/.Net. This is because it is the server that must determine if someone has logged in, not their own browser.
I will use PHP as the server language for this example.
A great tool for keeping track of whether someone has been authenticated is PHP $_SESSIONs
<?php
session_start();
mysql_connect('localhost','my_cpanel_login_ID','my_cpanel_password') or die($connect_error); //or die(mysql_error());
mysql_select_db('cpanelLoginID_dbname') or die($connect_error);
if(isset($_SESSION['user_name'])===true) {
echo '<div id="my_act">Here is the information from their account</div>';
}else{
echo 'Login';
}
Here are some online video tutorials that may help:
PHPAcademy.org - used to be free, but is now just low-priced
Registration and Login tutorial
PHP and MySQL with PDO and mysqli_
TheNewBoston.com -- try this one:
Project Lisa - Unfinished tutorial but very good
Intro to PHP
Intro to jQuery
<html>
<head>
<script src="jquery.js"></script>
<script>
$j=jQuery.noConflict();
$j(document).ready(function()
{
$j("#my_act").show();
}
)
;
</script>
</head>
<body>
<div class="name" style="display:none" id="my_act">MY ACCOUNT</div>
</body>
</html>
Hope this helps !
This is not an answer, just an extended comment with some things (untested) for you to try:
Since entity has a value, you can try checking the length of the entityId. First, begin with an alert:
alert(entityId.length);
to ensure it does what we desire.
Then, something like:
if (entityId.length > 0) {
$j('#my_act').css('display','block');
}
BTW, are you sure that your jQuery.noConflict(); code is working correctly? Try something simple (without any if statements to add any additional layers of complexity):
$j('#my_act').css({'color':'red','font-size':'bold'});
Does that work?

Loading and changing iFrame 'src' from another page

I have a page with an iFrame and four links to native files that each appear correctly within the iFrame when summoned. I've done this with straight HTML. The problem is that when I land on the page initially I have an empty iFrame until I click any of the links.
Not only would it be nice to have the iFrame populated with the first link upon arrival, but it would be a real bonus if there was a way to arrive at this page with any other of the remaining links appearing, if in fact that's the content someone came looking for. For example, if I place anchors for my four links on another page, it would be ideal if someone could select the second item and find it populating the iFrame upon arrival at my-iFrame-page.php.
I'm not opposed to using jQuery nor javascripting of any kind, but I'm afraid that for a scripting novice, it's important that I understand the syntax. I'd be over the moon if someone could post a working example that achieves what I'm after.
You can set the src="" attribute for the iframe which will set the default page.
For example, if I place anchors for my four links on another page, it would be ideal if someone could select the second item and find it populating the iFrame upon arrival at my-iFrame-page.php.
Needless to say, if you have a preceding page which links to that which contains the iframe, you can pass the url selected as a parameter in the request to the iframe page and then parse it into the attribute with PHP.
For simplicity's sake, let's imagine that you have two pages: sourcepage.php and framepage.php. sourcepage.php contains a form with four radio buttons plus a submit button which submits to framepage.php. The radio buttons are all part of the same set, and have four values--as per your comment "Apples", "Bananas", "Cherries" and "Peaches". The Apples radio has a value of 1, Bananas 2 and so on. Each radio has the name "page".
What this means is that when you submit the form, on sourcepage.php you need the following code
<?php
$pageIndex = $_GET["page"];
$pageUrl = "";
switch ($pageIndex)
{
case "1":
$pageUrl = "apples.html";
break;
case "2":
$pageUrl = "bananas.html";
break;
// And so on...
}
?>
<!-- And then later... -->
<iframe src="<?php echo $pageUrl; ?>"></iframe>
Use JS to get an URL paramater, and ofcourse add a paramater to the links in your footer. Assuming your iframe has id="iframe", this does the trick :)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function() {
function get_url_param(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) {
return "";
} else {
return results[1];
}
}
if (get_url_param('show') == '') {
$('#iframe').attr('src', 'wall-structures.php'); // Setting your default page....
} else {
$('#iframe').attr('src', get_url_param('show') + '.php');
}
});
</script>
</head>
<body>
Wall & Structures<br />
Ovens & Barbecures<br />
Pillars & Arches<br />
Stairs & Retaining Walls<br />
<iframe id="iframe"></iframe>
</body>
</html>
If you don't want to use JS, it can also be done in pure PHP:
<?php
if (isset($_GET['show'])) {
$iframe_src = $_GET['show'] . '.php';
} else {
$iframe_src = 'somedefaultpage.php';
}
?>
Wall & Structures<br />
Ovens & Barbecures<br />
Pillars & Arches<br />
Stairs & Retaining Walls<br />
<iframe src="<?php echo $iframe_src; ?>"></iframe>

Javascript - getElementById.innerHTML Problem

I want to create a simple formular which leads the user to 2 different pages (depending on what they choose). I'am using getElementById.innerHTML to differ the code within the site to create the two different <form action="SENDTHEUSERHERE" method="POST">-HTML-Elements.
Here's the code:
if (blabla which works)
{
document.getElementById("insert").innerHTML = "<form action='insert.php' method='POST'>";
}
else if (blabla which works)
{
document.getElementById("service").innerHTML = "<form action='service.php' method='POST'>";
}
// MORE BLABLA-CODE
<span id='insert'></span>
<span id='service'></span>
// REST OF THE FORMULAR
When I'am sending this formular, it leads me simply to the same page it was sent from. I guess that means, that those .innerHTML-Elements aren't recognized. Have you any suggestions how I can solve this? Btw.. yes, I'am a Javascript Noob -_-
Thanks for any help!
Just change the form action instead of using innerHTML...
if (conditionOne) {
document.forms['formName'].action = 'insert.php';
} else if (conditionTwo) {
document.forms['formName'].action = 'service.php';
} else {
alert('Error!');
}
You're going to have to post either your full HTML page + javascript code or a working example showing the problem. From the little you posted, it's impossible to tell what could be wrong.
But, that said, you're going about this problem in the wrong way. Instead of changing the innerHTML of some nodes, have one form with no action, and then in javascript do something like:
<form id="myForm">
var myForm = document.getElementById( "myForm" );
myForm.action = ( someConditionHere ) ? "insert.php" : "service.php";
If your example is what you need to do, you can just modify the action attribute of an existing form.
<form method='post' action='nowhere'>
<stuff>
</form>
<script type='text/javascript'>
if (something) {
document.forms[0].action = 'insert.php';
} else {
//etc
}
</script>

Categories