Prepopulate and submit hidden form - javascript

I have a form and here's the handler for the submit button:
$( '#submit_btn' ).click( function( data ){
theForm = document.getElementById( 'realForm' );
theForm.meetingName.value = document.getElementById( 'meeting_name' ).value;
theForm.meetingId.value = '';
theForm.description.value = document.getElementById( 'mtg_description' ).value;
theForm.startTime.value = startDate + ' ' + startTime;
theForm.endTime.value = endDate + ' ' + endTime;
theForm.loginName.value = participants;
theForm.role.value = roles;
theForm.docRights.value = docRights;
theForm.submit();
});
This handler basically pre-processes some data and sends to a hidden form, this:
<form id="realForm" style="visibility:hidden" action="/app/meeting/create" method="post">
<input name="loginName" type="text">
<input name="meetingName" type="text">
<input name="meetingId" type="text">
<input name="startTime" type="text">
<input name="endTime" type="text">
<input name="description" type="text">
<input name="roles" type="text">
<input name="docRights" type="text">
</form>
Problem is that the request isn't hitting the endpoint defined in the hidden form. What am I doing wrong here?
I've changed to make the input types hidden instead of the form. The submit handler certainly executes and, using FireBug, I don't see the request going out under the NET tab.
I'm using this dummy data to try and trigger the request but it's still not working:
theForm.meetingName.value = "MY MTG";
theForm.meetingId.value = '';
theForm.description.value = "DESC";
theForm.startTime.value = "2013-05-25 00:00:00";
theForm.endTime.value = "2013-05-25 02:00:00";
theForm.loginName.value = "foo#frr.com";
theForm.role.value = "M,M";
theForm.docRights.value = "CRUT,CRUT";

I'd try this out:
document.forms.realForm.submit()

2 tips:
use this for fetching variable from input.
$("#NAME_OF_YOUR_INPUT_ID").val();
use hidden input instead and identify each one with ID.
<input id="docRights" type="hidden">

The problem is that my first form had a button with type = "submit"...so that was submitting the form even though I didn't want it to.
I had to change the type to "button" in order to prevent that from happening.
Thanks for all the prompt responses.

Your input name is roles not role.
Change your line of JS to:
theForm.roles.value = roles;
See JS Fiddle: http://jsfiddle.net/jav6s/

Related

User input to build URL

I have a bit of experience with HTML but am very new to JavaScript. In essence, I would like for a user input to be part of a URL. For example, we could have something simple such as:
<script>
function get_cityname() {
var cityname = document.getElementById("cn").value;
alert(cityname);
}
</script>
<form>
Enter city name:
<input type = "text" size = "12" id = "cn">
<input type = "submit" onclick = "get_cityname();">
</form>
This will create a textbox where a user inputs their text (city name) and then click the 'submit' button next to it, and an alert should pop up based on the information they provided, just to make sure this works. However, this code only would seem to work (because of the 'onclick' command) to work for one user input. Therefore, I have 2 questions:
How could the above variable be included in a URL string? If it were something simple as:
URLstring = "https://sampleurl" + cityname + "moretext.html"
How could this be expanded if I want to include two or possibly even n number of inputs? For example, if I create more user prompt boxes and want to have the user also be able to input their zipcode, or state abbreviation, for example:
URLstring = "https://sampleurl" + cityname + "moretext" + zipcode + "moretext" + "stateabbreviation.html"
You could do something along these lines (it would be the same for one or more fields):
// Ensures the DOM (html) is loaded before trying to use the elements
window.addEventListener('DOMContentLoaded', function() {
var cnInput = document.getElementById("cn"),
zipInput = document.getElementById("zip"),
form = document.getElementById("myForm");
form.addEventListener('submit', getUrl); // On submit btn click, or pressing Enter
function getUrl(e) {
var cityname = cnInput.value,
zipcode = zipInput.value,
url = "https://sample.com/" + cityname + "/" + zipcode + ".html";
alert(url);
e.preventDefault(); // Prevent the form from redirecting?
}
});
<form id="myForm">
<label>Enter city name: <input type="text" size="12" id="cn"></label>
<label>Enter zip code: <input type="text" size="12" id="zip"></label>
<input type="submit">
</form>
First specify an action attribute for your form. This is where your form will be submitted. Then set your form's method attribute to GET. Finally, add as many fields as you like (I am assuming you are after a GET query such as https:url.com?key1=val1&key2=val2...):
<form method="GET" action="https://sampleurl">
Enter city name:
<input type="text" size="12" id="cn">
Enter zip code:
<input type="text" pattern="[0-9]{5}"
<input type="submit" ">
</form>

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

Pass js variable to form action url

I'm not sure if this is possible, or if I am doing it the wrong way?
I have a form that when submitted, should send the user to a URL depending on the input.
e.g If the users inputs '2', the URL should be books/itemView?id=2
I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?
My current code is as follows;
<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>
My JS
$(document).ready(function(){
var id = $('#search').val();
});
Quite new to JS so any help appreciated.
JS should be
$('#search').on('submit', function() {
var id = $('#demo').val();
var formAction = $('#search').attr('action');
$('#search').attr('action', formAction + id);
});
If they enter 2 in the search input then your id will be appended to your url like:
url?search=2
So maybe you want to change the name of your search input to id or add another input field.
<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>
That should be all you need no jquery or javascript necessary.
When you submit it should result in:
books/itemView?id=2(or whatever is in the search/id input when you click submit)
Hmm, you can try with that:
$(document).ready(function(){
var $form = $('#search');
var id = $form.val();
var $search = $('#demo');
var originalAction = $search.attr('action');
$form.on('submit', function() {
$search.attr('action', originalAction + id);
});
});
Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.
originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.

Can't set the submit type input in a form created with Java Script

I am working on a project where I have to carryout CSRF on a web page. So when the user is logged in and when he clicks on my webpage, I have to post with his username(derived from the cookie) .
I tried creating my own form using the following code , So that when the user clicks my webpage, this form will post into post.php(target webpage)
<html>
<script language="javascript">
function blah() {
alert();
var theForm, newInput1, newInput2, newInput3;
var bla = "Aaada";
var bla2 ="POST";
// Start by creating a <form>
theForm = document.createElement("form");
theForm.action = "http://targeturl/post.php";
theForm.method = "post";
newInput1 = document.createElement("input");
newInput1.type = "text";
newInput1.name = "username";
newInput1.value = bla;
newInput2 = document.createElement("textarea");
newInput2.name = "message";
newInput2.value = bla;
newInput2.id = "message";
newInput3 = document.createElement("input");
newInput3.type = "submit";
newInput3.name = "post_submit";
newInput3.value = bla2;
newInput3.id = "post_submit";
theForm.appendChild(newInput3);
theForm.appendChild(newInput2);
theForm.appendChild(newInput1);
theForm.submit();
}
blah();
</script>
</html>
Title, Message and Submit button are the three inputs in the target form.
When I try running this form, the submit button alone is not set. I am not able to understand why. I tried an actual form in html (with ) and posted it to the target URL, it works .
But since I have to be stealthy, I have to manually build the form , like the code I have posted. I tried all posssibilites and I am not able to nail the actual reason why this variable is not setting.
PS:
if (isset($_POST['post_submit'])) {
is the check in target page
and below id the target form :
<form method="post" action="post.php">
Title: <input type="text" name="title" maxlength="50"/>
<br />
<br />
Posting:
<br />
<br />
<textarea name="message" cols="120" rows="10" id="message"></textarea>
<br />
<br />
<input name="post_submit" type="submit" id="post_submit" value="POST" />
</form>
(It posts to itself, I have not included the remaining code of target)
Any help would be appreciated
Thanks
If you trigger the click event instead of the submit event, you'll get the submit button as well, so replace
theForm.submit();
with
newInput3.click();
add document.body.appendChild(theForm); in java script
before submit and enclose your function call as :
window.onload = function() {
blah();
}
else you will get document.body is null error in js

How do I get the value from form input into a variable

Just started learning Javascript today and I'm stuck. The page just reloads when I submit. Am I putting .value in the wrong place? Maybe some other noob mistake?
<script type="text/javascript">
function Calculate() {
var volume = document.getElementById('volume').value;
var carbonation = document.getElementById('carbonation').value;
var temperature = document.getElementById('temperature').value;
var sucrose = (15.195 * volume * (carbonation - 3.0378 + (0.050062 * temperature) - (0.00026555 * (temperature * temperature))))/28.4;
var dextrose = sucrose + (sucrose * 0.15);
document.write('<div id="result">You need ' + math.round(dextrose * 100)/100 + ' ounces of dextrose</div>');}
</script>
<form>
<input id="volume" type="text">
<input id="carbonation" type="text">
<input id="temperature" type="text">
<input type="submit" onclick="Calculate();" value="Calculate">
</form>
You need to put
return false;
At the end of your function so that the page doesn't reload.
Like this
function Calculate() {
// All Code here...
}
This will prevent the form from being submitted.
And instead of attaching the click event you need to use the submit event
Add ID to the form
<form id="myForm">
Listen for when the form is submitted
var myForm = document.getElementById('myForm');
myForm.onsubmit = Calculate;
And change your button to
<input type="submit" value="Calculate">
Form submitting will happen before the function is executed, therefore the page will reload instead of running your function when you click that button.
Use an <input type="button"> instead.

Categories