Javascript - getElementById.innerHTML Problem - javascript

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>

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>

Refresh chart(javascript) after doing mysql Query

I've got a javascript for drawing a chart. I get my information out of my MySQL base. And I got 3 different buttons to get the different information out of the database.
My problem now is, I get the information out of my database, it shows it in the chart but when it shows the information it refreshes the page.
Is there a way to show the information after my page is refreshed? I actually tried to use the window.onload but that doesn't give me the wanted result.
in php I use the following code to get the info from my MySQL DB:
if(isset($_POST['btnProduct']))
{
....
}
in html it's like this:
<div class="content">
<form action="" method="post" enctype="multipart/form-data">
<input type="submit" name="btnProduct" id="btnFilterProduct">
</form>
</div>
And in JS I use this code:
<script type="text/javascript">
window.onload = function()
{
document.getElementById('btnFilterProduct').onclick = function()
{
....
}
}
I know the PHP needs to refresh to get the data. and Javascript doesn't. But can I change the order? Or is there a way to change my JS to let it load AFTER the page is refreshed?
To stop the page reload, modify your onclick function to be:
document.getElementById('btnFilterProduct').onclick = function(event) {
event.preventDefault();
...
}
event.preventDefault stops the default behavior of the event, which in this case is to refresh the page since you have an empty action. Another option would be to not use a form. Just use the <button> element instead.

Make duplicate html document with autogenerated name

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

Sending data with javascript to PHP

I want to send the data and the Text that is in one DIV tag with Javascript into php values.
I have problem with using this code :
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
<script>
$.post('http://localhost/test/index.php', {
name: $('.class').html()});
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.class').text();
$(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
});
});
</script>
<form action="" method="POST" id="my_form">
<div class="class" name="name">
this is my div
</div>
<input type="submit" value="submit" name="submit" />
</form>
<?php
if (isset($_POST['name'])) {
echo $_POST['name'];
}
It doesn't work . Nothing appear ! and NO php working !
How can i solve this problem ?
You have stated you would like to do the following:
I want to send the data and the Text that is in one DIV tag with
Javascript into php values.
And
It doesn't work . Nothing appear ! and NO php working !
First you need to decide on what "appear" means. Are you trying to take the results of the PHP script and embed them on the page?
First, let's focus on your first item, sending the data. Please do the following:
Remove the onReady statements from inside the post request you're making. This is confusing and could result in unexpected results:
$.post('http://localhost/test/index.php', {
name: $('.class').html()});
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.class').text();
$(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
});
});
Readability is key here. This is absolutely bizarre looking and I've never seen anyone do it this way.
Notice I changed your class from .html() to .text(). This is because you're only working with a text node and not html at this point given your example code. If it were actually html, then you could use the html() function.
Second, the PHP script you're trying to hit is embedded directly.
Try moving it to a new file, such as in my above example myPhpScript.php
Inside that file would be your PHP code that fields the post request:
<?php
if (isset($_POST['name'])) {
echo $_POST['name'];
You're missing an on success handler in your POST request, so when the request success, nothing is going to happen. Please add the following to your request setup object. AT this point you can do the following with your on ready as well
$(document).ready(function(){
$.post('http://localhost/test/myPhpScript.php', {
name: $('.class').html()}
,function(data){
$(".class").text(data).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
}
});
});
This should get you started, but keep in mind there could be other issues as well. I've got my own share of issues in here as well. I'm going to blame lack of caffeine and a toddler, plus not keeping the documentation open long enough to make sure I get it perfect :).
Someone was kind enough to edit my mistakes, so for that I thank you.
That is because you didn't specify a success handler for your $.post request. So all it does is return some HTML like you have in the background, but your JavaScript isn't doing anything with it.
Please read the API docs on http://api.jquery.com/jquery.post/ and check the success(data, textStatus, jqXHR) part of the arguments to $.post. That is where you define your success handler.
Try this and you'll see what I mean:
$.post('http://localhost/test/index.php', {
name: $('.class').html()
}, function(data) {
alert(data);
});
Within the function(data) { ... } you need to program some logic so it does something with your data.

Replacing GET with POST

Here I am trying to redirect new page and I want to send a variable. It uses GET.
How can I do it with POST?
window.location.href = 'start.php?userid='+userid;
start.php
<?php
$user_id=$_GET['userid']; //should be post
?>
You will have to submit the data to the server, not just redirect the browser.
In your case, as it looks like you want full page refresh anyway just create a form on the fly:
var oForm = document.createElement("form");
oForm.method = "POST";
oForm.action = "start.php";
var oInput = document.createElement("input");
oInput.name = "userid";
oInput.value = userid;
oForm.appendChild(oInput);
document.body.appendChild(oForm);
oForm.submit();
You need to declare a fake form in HTML and a link that will trigger javascript to submit the form, like below
<form action="start.php" method="post">
<input type="hidden" name="userid" value="[userid]">
</form>
<script type="text/javascript">
function submitlink()
{
document.forms[0].submit();
}
</script>
<a class="buttondown" onclick="submitlink()">Submit Link</a>
I think this answer may help you:
How do you force a web browser to use POST when getting a url?
You just need to create a form on demand using javascript to send data with POST method when clicking a link.
So basically it's just this part:
<script type="text/javascript">
function submitAsPost(url) {
var postForm = document.createElement('form');
postForm.action = url;
postForm.method = 'post';
var bodyTag = document.getElementsByTagName('body')[0];
bodyTag.appendChild(postForm);
postForm.submit();
}
</script>
this is my post link
I was in the same problem you had. If you are using jquery.redirect.min.js as your jquery plugin, You can use as below. It gives you POST method.
$().redirect("myPhp.php", { name: "John" });
All you need is to download jquery.redirect.min.js file from here and link it with your php file, and use as above. That's it. Hope I helped.
Works fine for me.
You can post form by html tag and . Otherwise, see "jQuery.post" for async post.
For the 1st case you create FORM tag, put INPUT type="hidden" inside and set its value that will be posted.

Categories