HTML form data to local JSON file without Node.js - javascript

So I'm building a web application with the option to be admin and add data to a JSON file, which will be displayed onto another HTML page (index).
Now is my question: how to do it. How to get the data from the form, parse it, and put it in a JSON file. And can it be done without Node.js
This is my current JSON-file
{"accounts": [
{"email": "example-mail#mail.com", "password2":"Duck123"},
{"email": "example-mail2#mail.com", "password2":"Cow123"},
{"email" : "example-mail3#mail.com", "password2": "Chicken123"}
]}
This is my "Admin" page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>ADMIN PAGE</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<form id="adminform" action="#" method="post">
<div class="form-group">
<label for="emailadress">Email Address</label>
<input type="email" class="form-control" id="emailadress" required autocomplete="false">
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" class="form-control" id="password2" required>
<input type="button" value="Show Password" readonly onclick="passwordShow()" autocomplete="false">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
<script>
//show password on button click
function passwordShow() {
var x = document.getElementById("password2");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>
</html>
If somebody knows how to do it, or has a tip, please let me know!

Direct writing to the filesystem can not be done from inside the Browser. However you have the possibility to create a "download" link, so that the user gets a notification that a file should be downloaded and can pick a location where to store that file.
Copied the following snippet from Stackoverflow: Download JSON object as a file from browser. You can use it to create exactly that download containing your json content.
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}

Related

PHP mysql data vs js dynamic fields

I have a piece of code (in a .php file) that can dynamically add/remove a group of input fields by JavaScript.
<!DOCTYPE html>
<!-- ref: https://stackoverflow.com/questions/75408002/javascript-dynamically-add-and-remove-input-fields -->
<html lang="en">
<head>
<style>
#template #template_p{ display: none }
</style>
</head>
<body>
<form action="" method="post" autocomplete="off">
<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<div id="placeholder">
<div id="template">
<fieldset id="template_fieldset">
<legend>Group</legend>
<p>Item <input type ="text" name="prof_item[]" /><br /></p>
<p>Duration <input type ="text" name="prof_duration[]" /><br /></p>
<p id="template_p"><button type ="button" name="prof_remove[]" onclick="this.closest('div').remove()">Remove group</button><br /></p>
</fieldset>
</div> <!-- template -->
</div> <!-- placeholder -->
<p><button type="button" name="add" onclick="Add();">Add new group</button></p>
</fieldset>
<p><button type="submit" name="Submit">Submit</button></p>
</form>
<script>
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder").appendChild(oClone);
}
</script>
</body>
</html>
Using this and adding some PHP code, user data can be collected and saved into MySQL. When the user comes back, is it possible to add the ability to populate the loaded user data into the page, and the user can still dynamically add/remove a group of input fields? I understand that PHP is run on the server and JavaScript is on the client side.

Save form data to text file - HTML & Javascript

I am not worried about security, this is just a small project, which I am using only on my computer. I need to store a .txt file with data from a login form to the same location that the HTML file is. I don't think you can do it with javascript, but I don't know anything about PHP and I have tried many times to get this to work, but it isn't. Here is my code.
<form style="text-align: center;" action="./success.html" method="post">
<div class="form-group">
<label for="username">Username</label>
<input placeholder="Username" autocomplete="off" type="text" id="username" name="username"><br>
</div>
<div class="form-group">
<label for="password">Password</label>
<input placeholder="Password" autocomplete="off" type="password" id="password" name="password"><br><br>
</div>
<input id="button1" class="btn btn-success" type="submit" value="Sign Up">
<!-- When pressed, needs to store data in a data.txt file. -->
</form>
How would I be able to do this if I'm using this setup, and what would I need to change?
I'll just show you a quick example to get you started and create a JSON file with some data like:
{"username":"Lorem", "password":"ipsum"}
Rather than into .txt use a .json file. It's the today's most popular standard for storage and transmit of structured data.
Use AJAX to send a request and receive a response - without page refresh
Use json_encode the nifty PHP's file_put_content
Use JS's fetch ("POST") with the data being the FormData
Run the demo using php -S localhost:81 and open it in your browser:
save.php
<?php
if (
$_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST["username"])
&& isset($_POST["password"])
) {
$json = json_encode($_POST);
// Save JSON to file
file_put_contents("user.json", $json);
// Return some data back to the AJAX request.
echo $json;
// PS it's not wise to send passwords that way.
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="#!" type="image/x-icon">
<title>AJAX PHP - SAVE USER DATA </title>
</head>
<body>
<h1>User: <span data-username>Unknown</span></h1>
<form id="form-login" action="./save.php" method="post">
<div class="form-group">
<label>
<span>Username</span>
<input placeholder="Username" autocomplete="off" type="text" name="username">
</label>
</div>
<div class="form-group">
<label>
<span>Password</span>
<input placeholder="Password" autocomplete="off" type="password" name="password">
</label>
</div>
<input id="button1" class="btn btn-success" type="submit" value="Login">
</form>
<script>
const EL_formLogin = document.querySelector("#form-login");
EL_formLogin.addEventListener("submit", (ev) => {
ev.preventDefault(); // Stop default form submit - we'll use AJAX
fetch(EL_formLogin.action, {
method: 'POST',
body: new FormData(EL_formLogin),
}).then(res => res.json()).then(data => {
// Hide the form
EL_formLogin.hidden = true;
// Show the user name
document.querySelector("[data-username]").textContent = data.username;
});
});
</script>
</body>
</html>
DISCLAIMER!
Never store passwords in plaintext on your server files or database - and only send passwords over HTTPS.

How to add links in mesage in popup window in javascript alert?

I have a function which stores the data and after that function I wanted to give an popup message with link. I am able to submit data and create an popup using alert. But adding link in text is something I want. Below is the code I tried.
<!DOCTYPE html>
<html>
<base target="_top">
<head>
<script type="text/javascript">
function myfunction(from){
(function($){
var id = $("#id");
var wnum = $("#wnum");
var id = id[0]['value']
var wnum = wnum[0]['value']
if(from == 'submit'){
submitData(id,wnum) // data submitted
var str = "Inform us!";
var result = str.link("some_link");
alert("Thank you for submitting the form. "+result);
}
})(jQuery);
}
</script>
<body>
<div class="cen">
<div class="wrapper">
<h1>Font Selector</h1>
<fieldset class="fontForm grid">
<div class="grid-cell">
<div class="grid-cell size1of1">
<label for="fname">Order Id</label>
<input type="text" id="id" name="id" placeholder="Enter order id" >
<label for="fname">WhatsApp Number</label>
<input type="text" id="wnum" name="wnum" placeholder="Enter WhatsApp number">
<p><button onclick="myfunction('submit')">Submit</button></p>
</div>
</div>
</body>
</html>
How could I do this?
You cannot with alert. You will have to build an alert dialog that does not use it, e.g. using bootbox or something you build yourself.

Zendesk App Error & Delayed/Failed Webhook Post

I am building a Zendesk app that will post a variety of information to a webhook. Currently, I am running into two issues. The client.invoke() function says it is not a function in the console when the send email button is pressed. Additionally, sometimes the after the button is pressed, the app will successfully post to the webhook, other times it won't post at all. I cannot narrow down what is causing the discrepancies on when it posts. I'm unsure if this is related to the app I've built or an issue interacting with Zendesk.
Here is the app:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="main.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://assets.zendesk.com/apps/sdk/2.0/zaf_sdk.js"></script>
<script src="https://cdn.jsdelivr.net/handlebarsjs/4.0.8/handlebars.min.js"></script>
</head>
<body>
<script>
var client = ZAFClient.init();
client.invoke('resize', { width: '100%', height: '450px' });
client.get('ticket.brand.subdomain').then(
function(data) {
var subdomain = data['ticket.brand.subdomain'];
console.log('Zendesk Subdomain is ' + subdomain);
document.getElementById('subdomainform').value = subdomain;
}
);
client.get('ticket.organization.id').then(
function(data) {
var org_id = data['ticket.organization.id'];
console.log('Org id is ' + org_id);
document.getElementById('orgidform').value = org_id;
}
);
</script>
<form name="submissionForm">
<div class="formBox">
<label for="title">First Name</label>
<input type="text" id="firstName" placeholder="First Name"/>
</div>
<div class="formBox">
<label for="title">Last Name</label>
<input type="text" id="lastName" placeholder="Last Name"/>
</div>
<div class="formBox">
<label for="title">Email</label>
<input type="text" id="email" placeholder="Email"/>
</div>
<div class="formBox">
<select id="rescom">
<option value="residential">Residential</option>
<option value="commercial">Commercial</option>
</select>
</div>
<div class="formBox">
<button id="btn">Click to Send Email</button>
</div>
<div><p id="explain">The fields below are ready-only and required for submission. If you don't see them, please refresh the app.</p></div>
<div class="formBox">
<input type="text" id="subdomainform" readonly="readonly"/>
</div>
<div class="formBox">
<input type="text" id="orgidform" readonly="readonly"/>
</div>
</form>
<script>
let content = [];
const addDay1 = (ev)=>{
let information = {
id: Date.now(),
firstName: document.getElementById('firstName').value,
lastName: document.getElementById('lastName').value,
email: document.getElementById('email').value,
subdomain: document.getElementById('subdomainform').value,
orgid: document.getElementById('orgidform').value,
rescom: document.getElementById('rescom').value
}
content.push(content);
document.forms[0].reset();
const Url ='{PLACEHOLDER}';
$.ajax({
url: "{WEBHOOK URL}",
type: "POST",
dataType: 'json',
data: {information},
complete: function(){alert("Failure")}
});
}
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById('btn').addEventListener('click', addDay1);
});
</script>
</body>
</html>
What am I missing? Appreciate any and all help that can be provided.
This was solved my a community manager from Zendesk. See post below:
Make sure ZAFClient is fully registered before attempting to do
subsequent ZAFClient methods. Something like:
client.on('app.registered', e => {
client.get('ticket.brand.subdomain').then(
function(data) {
var subdomain = data['ticket.brand.subdomain'];
console.log('Zendesk Subdomain is ' + subdomain);
document.getElementById('subdomainform').value = subdomain;
}
);
client.get('ticket.organization').then(
function(data) {
var org_id = data['ticket.organization.id'];
console.log('Org id is ' + org_id);
document.getElementById('orgidform').value = org_id;
}
);
}) The "not a function in the console" error is caused from the app's HTML page being resubmitted again when you click the button. In
Zendesk Apps framework, the connection from the app (using
ZAFClient.init()) to the main agent window is done through parameters
that are passed to the app when the framework first loads it. You can
see this in your browser's Network tab if you look for something like
"iframe.html?origin=https%3A%2F%2Fyour_subdomain.zendesk.com&app_guid=ff7133010-abff-4f1c-a7bf-ff7133fff7133"
-- the origin and app_guid params are needed to make the connection. When you resubmit the page, those parameters no longer are passed on
the new page reload and the new call to ZAFClient.init() doesn't
successfully initialize. Thus leading the error when the now invalid
'client' object is attempting to be used to call 'invoke'. You have to
treat these app pages like single-page apps.
Phew! All that said -- you can still use HTML functionality,
just don't have it resubmit the entire page when the button is
pressed. You can do this by adding type="button" to the button tag.
Click to Send Email
See also: HTML button to NOT submit form
Hope this gets you on your way!

I can't get Tag content with a Script/Function

i'm with a ridiculous problem (i think). I just can't get a tag content using a Script/Function/document.getElementById. The alert tha i'm using to see the content of variable (wM) is always blank. I looked a lot of examples in the Web and all of them is similar, sometimes just like my code. See below:
<!DOCTYPE html>
<html lang ="pt-br">
<head>
<title> loginServlet2 </title>
<meta http-equiv = ”Content-Type” content=”text/html; charset=UTF-8”>
<link rel="stylesheet" type="text/css" href="c:/java/html/css/estilo.css"/>
<script type="text/javascript">
function oMsg()
{
var wM = document.getElementById("wMsgB").textContent;
// var wM = document.querySelector("span").textContent;
alert("wM = "+ wM);
if (wM == "Teste OK!")
{
// document.getElementById("wMsgA").innerHTML = "Test is OK";
document.getElementById("wMsgA").textContent = "Test is OK";
}
else
{
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h3> MsgB : <span id="wMsgB"<%=request.getAttribute("wMsg")%></span></h3>
<p> MsgA : <span id="wMsgA"> </span> </p>
</body>
</html>
Could anyone help me, please? Thanks.
You are trying to get the value of a p element, but p elements don't have a value property. Only form fields do. Non-form fields that contain text between their opening and closing tags have .textContent and .innerHTML properties you can use to get/set their contents.
If you want to give the user a place to type in some data, you need to create some input form fields and then you have to wait until they've done that before attempting to get the values.
Next, you have smart quotes “” instead of straight quotes "" which can cause encoding problems. Make sure you write your code in an editor that doesn't apply any formatting to the code. There are plenty of great free web editors out there.
You also have a reference to a .css file using a full local path, which isn't going to work when you deploy this code later. You should be using relative paths to reference files that are part of your system.
Finally, you are using some old HTML syntax in your meta, link and script tags, so take note of the modern versions of those in the snippet below.
<head>
<title>loginServlet2</title>
<meta charset=UTF-8”>
<link rel="stylesheet" href="c:/java/html/css/estilo.css"/>
<script>
function oMsg() {
var wM = document.getElementById("wMsg").textContent;
alert("wM = " + wM);
if (wM == "Test OK!") {
document.getElementById("wMsgA").textContent = "Test is OK";
} else {
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h2>MsgB : <span id="wMsg"><%=request.getAttribute("wMsg")%></span> </h2>
<p>MsgA : <span id="wMsgA"> </span> </p>

Categories

Resources