Set form action with JavaScript - javascript

I have a basic form. I have hidden inputs outside the form. I want to set the form action with JavaScript to include the values from the hidden parameters as variables in the GET of the form when the user press the enter/submit button.
The form's current action is "https://example.com". I want to use JavaScript to take the values from the hidden inputs and concatenate them to the form's action so that the information stored outside the form is submitted with the form.
For example, the desired output for the form's action would be "https://example.com?firstParameter=parameter&secondParameter=secondParameter".
Here is what I have so far.
<form action="https://example.com" method="GET">
<input type="text"></input>
<button type="submit"></button>
</form>
<input type="hidden" id="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" value="anotherParameter">
<script>
function setFormAction() {
var firstParameter= $("#firstParameter").val();
var secondParameter= $("#secondParameter").val();
var url = "https://example.com?";
if(firstParameter!== ""){
url = url + "&firstParameter=" + firstParameter;
}
if(secondParameter!== ""){
url = url + "&secondParameter=" + secondParameter;
}
// form action = url; (Need help here)
}
</script>

A simpler solution might be to add names to the hidden inputs then append them to the form so they get submitted by default process.
HTML
<input type="hidden" id="firstParameter" name="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" name="secondParameter" value="anotherParameter">
JS
$('form').submit(function(){
const $form = $(this);
$('#firstParameter, #secondParameter').each(function(){
if(this.value){
$form.append(this)
}
});
});

Try the following:
document.querySelector('form').setAttribute('action', url);
function setFormAction() {
var firstParameter = $("#firstParameter").val();
var secondParameter = $("#secondParameter").val();
var url = "https://example.com";
if (firstParameter !== "") {
url = url + "&firstParameter=" + firstParameter;
}
if (secondParameter !== "") {
url = url + "&secondParameter=" + secondParameter;
}
document.querySelector('form').setAttribute('action', url);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://example.com" method="GET">
<input type="text" />
<button type="button" onclick="setFormAction()">Test</button>
</form>
<input type="hidden" id="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" value="anotherParameter">
Use encodeURIComponent() in case of user input to sanitise it.

I think you should avoid using form submission if you are not actually submitting a form in the general sense and use a simple button with an event to a function. You can then declare states which do different things with the submission like:
<button id="submit-button">Submit</button>
let state = 'default'
function onFormSubmit()
{
if (state == 'default') doDefaultThings()
else doLessDefaultThings()
}
async function doDefaultThings()
{
//collect necessary data
let url = "https://example.com" //append here
let res = await fetch(url)
//do other things or redirect
}
document.getElementById('submit-button'
.addEventListener('click', onFormSubmit)

Related

How can I fix this html code to not display sensitive information to the user?

I am creating a html form to capture applicants' inputs and then send a POST request to an api with the data. I do not know how to go about hiding three specific values from something like 'View Page Source' or console.log(). I need to store the values securely and still be able to use them in the HTML form.
I know I will probably have to rewrite my solution but I do not know the best way to go about this. Is there a way to store the values of the api keys in a database?
Here are the three values in question:
<body>
<main role="main" class="container-fluid">
<form id="form1" name="form1" onsubmit="beforeSubmit(); return false;">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
<script type="text/javascript">
var merID = "1234567";//need to store these values somewhere else!!!!!!!
var log = "API123";
var pass = "1234567";
//even if these values are moved they would be viewable by something like console.log(obj)
document.getElementById("merchantID").value = merID;
document.getElementById("login").value = log;
document.getElementById("password").value = pass;
</script>
And here is where I make the API call:
<script type="text/javascript">
beforeSubmit = function () {
//======================================================================================================
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//======================================================================================================
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://someurl.com/enroll.svc/JSON/CreateMerchant", true);
xhttp.setRequestHeader("Content-type", "application/json");
var obj = JSON.stringify($('#form1').serializeObject());
console.log(obj);//security concern! all someone would have to do is cntrl+shift+j when the form is submitted
//this log command would display the entire JSON object including the merchant ID, Login and Password
xhttp.send(obj);
} //=====================================================================================================
</script>
I am very new to this. The code does what it is supposed to aside from sensitive information easily being viewed by inspecting the page source. Any suggestions of for a better/more secure way would be appreciated.
Its shouldn't be too hard put your api in a php variable then insert your variable into your database table.
Then use select to take it out when you need it also php is not readable from view source.
If you don't know how to input and select from databases there are plenty of tutorials out there.
Your code is a horrid mix of unnecessary serialisation you are not using and a weird event handling of beforesubmit.
This is how a generic jQuery ajax looks like
$(function() { // page load
$("#form1").on("submit", function(e) {
e.preventDefault(); // cancel the submit
$.post("https://someurl.com/enroll.svc/JSON/CreateMerchant", // url
$(this).serialize(), // serialising the form
function(result) {
console.log(result); // do something with the result of the submission
});
});
});
<form id="form1" name="form1">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
</form>

Multiple forms Ajax request using MVC pattern, get the new values of input fields

I'm retrieving forms from my page, using:
DOMS = {
form: '[data-form]',
}
document.querySelectorAll(DOMS.fom).forEach(function (form, index) {
arr[index] = {};
arr[index]['DOMRef'] = form;
}
and adding them to an object. I add an event:
addEventListener('submit', function (event) {
send(event, form);
});
Later on form submit, I retrieve the form, and loop thru it:
form = arr[1];
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i].type !== 'submit') {
data = data + form.elements[i].name + '=' + form.elements[i].value;
}
}
Above, I'm creating an Ajax request data. The problem is that I always retrieve the first value(without refresh).
If I change the value of a form field, is ignored, I presume because I call it from the object, and not again from DOM. Something like refresh form.
But also I don't want if is possible to call the form DOM everytime.
You are making copies of your forms somewhere, being called from object shouldn't affect.
document.addEventListener('submit', function (e) {
collectFormData(e);
});
let formsArr = document.querySelectorAll("form");
let formsObj = {fArr: formsArr};
function collectFormData(e){
e.preventDefault();
//event.target
var currForm = e.target;
for(i=0; i<currForm.elements.length; i++){
if(currForm.elements[i].type !== 'submit')
console.log(currForm.elements[i].value);
}
//array
for(j=0; j<formsArr[0].elements.length; j++){
console.log(formsArr[0].elements[j].value);
}
//object
for(k=0; k<formsObj.fArr[0].elements.length; k++){
console.log(formsObj.fArr[0].elements[k].value);
}
}
<form name="myForm" id="myform" action="" method="POST" enctype="multipart/form-datam">
<input type="text" class="val1" name="val1" id="val1" />
<input type="text" class="val2" name="val2" id="val2" />
<input type="text" class="val3" name="val3" id="val3" />
<button type="submit">submit</button>
</form>
PS. But also I don't want if is possible to call the form DOM everytime The value of the input field is in(side) the DOM. You can't get the gift without touching the package.

I have this code written in JavaScript what i'm doing wrong?

I have this code:
how can I make my code to work with both options? because now it only use one selection because I believe the code is not proper duplicated
<form action="https://track.aftership.com/tuffnells/" method="get" target="_blank" id="my-form">
<input type="text" name="reference-number" id="reference-number" value="" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var form = document.querySelector('#my-form'),
text_field = document.querySelector('#reference-number');
function submitHandler(){
// build the new url and open a new window
var url = form.action + text_field.value + '?tracking_account_number=318843';
window.open(url);
// prevent form from being submitted because we already
// called the request in a new window
return false;
}
// attach custom submit handler
form.onsubmit = submitHandler;
</script>
<form action="https://track.aftership.com/tnt-reference/" method="get" target="_blank" id="my-form1">
<input type="text" name="reference-number1" id="reference-number1" value="" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var form = document.querySelector('#my-form1'),
text_field = document.querySelector('#reference-number1');
function submitHandler(){
// build the new url and open a new window
var url = form.action + text_field.value + '?';
window.open(url);
// prevent form from being submitted because we already
// called the request in a new window
return false;
}
// attach custom submit handler
form.onsubmit = submitHandler;
</script>
how can i make this work twice, because now is working only once.
just rename your variables in the second script part, this:
var form = document.querySelector('#my-form1'),
text_field = document.querySelector('#reference-number1');
to:
var form1 = document.querySelector('#my-form1'),
text_field1 = document.querySelector('#reference-number1');
also change the (on the second script) :
var url = form.action + text_field.value + '?';
window.open(url);
to:
var url1 = form1.action + text_field1.value + '?';
window.open(url1);
here is a fiddle: https://jsfiddle.net/cLhvuy68/

Why do my DOM changes disappear when I click a form button?

This is my first post, so consider me a n00b.
I have created a simple form to access a value stored in a javascript array. I am trying to append an element to display the proper value. The logic works, my result will show, but only briefly, before it is overwritten. Can you help?
html
<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(document.getElementById('site').value)">
</form>
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>
javascript
var results = "";
function getFormData(val1) {
var pw = {
"site1": "xyzabc",
"site2": "defghi",
"site3": "jklmno",
"site4": "pqrstu",
"site5": ["id1", "vwxyza"],
"site6": ["id2", "bcdefg"],
"site7": "hijklm",
"site8": ["id3", "nopqrs"],
"site8": ["id4", "tuvwxy"],
"site9": ["id5", "zabcde"],
"site10": "fghijk",
"site11": ["id6", "lmnopq"],
"site12": "rstuvw"
};
results = pw[val1];
showResults(results);
}
function showResults(val2) {
var div = document.createElement('div');
var pss = document.createTextNode(val2);
div.style.color = "red";
div.appendChild(pss);
document.getElementById("result").appendChild(div);
}
You're actually submitting your form when you click the Submit button and page is reloading. Just change the type of button from submit to button:
<input type="button" value="Submit" onclick="getFormData(document.getElementById('site').value)">
Pass your Javascript function 2 arguments, the first is the event object, the second is the value you are passing. You can then use this to prevent the default behavior of a form (which is to submit the form and refresh the page)
<form>
<input type="text" label = "sitex" id="site"><br>
<input type = "submit" value = "Submit" onclick="getFormData(event, document.getElementById('site').value)">
<div id = "result"><p>Results:</p></div>
<script type="text/javascript" src="logic.js"></script>
then in your javascript, prevent the default behavior with .preventDefault();
var results = "";
function getFormData(event, val1) {
event.preventDefault();
var pw = {
"site1": "xyzabc",
"site2": "defghi",
"site3": "jklmno",
"site4": "pqrstu",
"site5": ["id1", "vwxyza"],
"site6": ["id2", "bcdefg"],
"site7": "hijklm",
"site8": ["id3", "nopqrs"],
"site8": ["id4", "tuvwxy"],
"site9": ["id5", "zabcde"],
"site10": "fghijk",
"site11": ["id6", "lmnopq"],
"site12": "rstuvw"
};
results = pw[val1];
showResults(results);
}

How to change the querystring when I submit my GET form using JQuery?

Suppose that I have a simple form in my page like this :
<form action="/properties/search" method="GET" id="form_search">
<p>
<label for="price">Min price:</label>
<input type="text" name="min_price" id="min_price">
</p>
<p>
<label for="price">Max price:</label>
<input type="text" name="max_price" id="max_price">
</p>
<p>
<input type="submit">
</p>
</form>
When I submit my form, I have the following url :
http://.../properties/search?min_price=100000&max_price=200000
I want to change this url to have :
http://.../properties/search?price=100000,200000
To do that, I'm using JQuery and the JQuery querystring plugin :
$(document).ready(function() {
$("#form_search").submit(function() {
var querystring = rewrite_interval_qstring();
// querystring equals "?price=100000,200000" -> exactly what I want !
// ???
});
});
How can I change (comment "???") the submit url ? I have tested the following instructions separately, but it does not work.
window.location = querystring;
window.location.href = querystring;
window.location.search = querystring;
You're almost there. Intercept the submit event (as you are doing), extract the min and max values, build your url and set window.location.href
$(document).ready(function() {
$("#form_search").submit(function(event) {
event.preventDefault();
$this = $(this);
// var url = rewrite_interval_qstring();
var min_price = $('#min_price').val();
var max_price = $('#max_price').val();
var url = $this.attr('action') + '?price=' + min_price + ',' + max_price;
window.location.href = url;
});
});
You need to prevent the default submit action from happening
$(document).ready(function() {
$("#form_search").submit(function(event) {
event.preventDefault(); // <-- add this
var querystring = rewrite_interval_qstring();
// querystring equals "?price=100000,200000" -> exactly what I want !
window.location.href = querystring; // <-- this should work.
});
});
Answer by Rob Cowie is one method. Another one is adding a hidden field named "price" and fill it before submitting it with the value you want.

Categories

Resources