Can't get a JS var inserted into a hidden field - javascript

I promise...I have researched this for over 24 hours. I know it is similar (if not exactly the same) as some other questions. I'm obviously missing something. (This is going to be a long-winded explanation...I apologize. Please don't let it scare you off...I'm pretty sure the root problem/question will be much easier than what all this looks like!)
End result desired is to get some JS vars POSTed over to my process PHP script from an HTML form. Simple, right?
I have a fully working form that does a bunch of calculations with a bunch of input fields...it's way too complex to post here...not to mention I really don't want to embarrass myself with what I'm sure is very bad coding!
In a nutshell...I have a function that in the process of running sets various JS vars. I need to get these vars inserted into some hidden input fields so that they will get moved over to my processing PHP along with all of the "normal" inputs. All of these vars represent floating point numbers (if that makes any diff)
Here is my form definition:
<form id="multiForm" action="App_post.php" method="POST" action="javascript:void(0)" id="appform" name="appform">
I have a "master" function that starts all of the calculations primarily based on when the user selects various radio buttons. Various selectors are dynamically updated in the form as the user selects buttons (which in reality is a user selecting different options of club membership fees and "add-on" items...someone is bound to ask what I'm doing!)
$(function () {
...lots of JS code here along with the calculations that create the JS vars I need
}
(I assume this function is called via the action="javascript:void(0)" )
Let's focus on just one var right now. The JS var "regularfee" (along with all the others I want) exists after all of the calculations are done. I need to have these values plugged into the hidden fields so that they can get POSTed.
Here is an example of the hidden field:
<input type="hidden" name="regularfee" id="regularfee" value="">
Here is where I am getting lost. I have done a console.log(regularfee) in the function right after all the calculations are done...it is set to the float number 26.5 (which is correct)
Here are a couple of things I have tried so far:
document.getElementById('regularfee').value=regularfee;
// --OR--
document.getElementById('regularfee').value=regularfee.value;
document.getElementById("app").submit();
No matter what I've tried, I get blank values POSTED over to my process PHP. Based on the other questions I've seen, the hidden input field method appears to be one of the "accepted" ways of doing this. I am not stuck on this method...just looking for the easiest way to get my vars POSTed! What am I missing? All help extremely appreciated!

Try regular post or use AJAX to SUbmit.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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;
};
This method gets all input in ur form including select and checked.
//multiForm form is your ID in ur form
var data = $("#multiForm :input").serializeObject();
after use ajax to save in php script.
$.ajax({
type: "POST",
url: "phpscript.php",
data: data,
success: function() {
alert("Input Success!");
}
});
How this will help you!

Technically, this syntax should be good to go...
document.getElementById('regularfee').value=regularfee;
This is assuming that the regularfee variable exists and it is of type float. Or even better use jQuery
$('#regularfee').val([your value here]);
Question, why do you have two actions in your form? How does it work?
<form id="multiForm" action="App_post.php" method="POST" action="javascript:void(0)" id="appform" name="appform">
Also, for peace of mind, also do a console.log to check the value of the hidden field after it's been set

You have two action attributes in your form. Remove the second one for "javascript:void(0)". It is not calling the function you think it is (the anonymous function you have there looks to be executed on dom ready).

Related

Sending a form through PHP, autosaving with JS every ten minutes

The Environment
PHP: Symfony -> Twig, Bootstrap
Doctrine -> Mongodb
Jquery
The Project
The timer is working, counting the interval, and I can send the form. This is good, but once I get to the part where the form is sent I seem to be running into two problems:
interval counter working
form submitting automatically, then
The null fields do not get accepted
The form does not get validated
The form itself is setup through a custom built PHP graphical interface that allows you to set the simple things very easily: fields, fieldtypes, names and labels, etc.
This is cool, but it means that you can't go in and tinker very much with the form or at all really. The most you can change is aesthetics in the template. Although you could wrap each form element in another form element or some kind of html identifier, this is an option, but a tedious one...
On a valid check the form gets upserted and all is well the else catches the non-valid form and lets the user know that some fields are not filled in. I would post that code here, but I think it would be frowned upon. Hopefully you understand the PHP concept.
The part that I can share is the JS:
autoSaveForm = function() {
var form = $('form'),
inputs = form.find('input');
form.on('submit', function() {
inputs.each( function( input ) {
if (input.attr("disabled") === true){
input.removeAttr("disabled");
}
})
});
function counter(){
var present = $('.minutes').attr('id'),
past = present;
$('.minutes').text(past);
setInterval(function(){
past--;
if(past>=0){
$('.minutes').text(past);
}
if(past==0){
$('.minutes').text(present);
}
},1000);
}
function disableInputs(){
inputs.each( function( input ) {
if (input.val() === ""){
input.attr("disabled", true);
}
});
}
// Start
counter();
// Loop
setInterval(function(){
counter();
form.submit()
},10000);
};
This sets a counter on the page and counts through an interval, it's set to seconds right now for testing, but eventually will be 10 minutes.
Possible Solutions
disable the null fields before submit and remove the attribute after submit is accomplished
this needs to be done so that the user can do a final completed save at the end of the process
this doesn't actaully seem to be disabling the fields
Their were a few things I found about adding in novalidate to the html, but it wasn't supported in all browsers and it might get tricky with the static nature of the forms.
Post the form with ajax and append a save true variable to the end of the url, then redirect it in PHP Controller with a check on the URI var although:
then I still have the null fields
to solve this: set a random value or default value to the fields as they are being passed through. haven't tried this yet
Something kind of like what this question is addressing, although I have some questions still about the null fields - Autosaving Form with Jquery and PHP
Sending the form through ajax
Any input would be greatly appreciated. :) Thanks

How to parse xml with js or jquery, when fields are not known in advance?

I have been searching for the past hour and have not found a solution that is well suited to my situation. I have an event registration form and in order for users to have the form auto populated they can specify an id from a previous registration. There are over 20 fields.
Everything is working pretty well. I have a PHP script that creates an xml response for ajax. The xml is of form
<response>
<field1>f1</field1>
<field1>f2</field1>
etc
</response>
My javascript is
$.ajax({
type : "POST",
url : "myscript.php",
data : $(this).serialize(),
success: function(xml){
$("#field1").val($("field1",xml).text());
$("#field2").val($("field2",xml).text());
}
})
Above works fine but I don't want to manually write out each form field assignment. I want to do it in a loop. So something like this in the success function:
var fields= xmlResponse.getElementsByTagName("response");
for (i = 0; i < fields.length; i++) {
// not sure what to put here...
}
In the for loop I have to index in to the node name and value so that I can simply have a statement that would be of this form: $("#"+fields[i].nodename).val($(fields[i].nodevalue,xml).text());
I tried
$("#" + fields[0].childNodes[i]).val(fields[0].childNodes[i].nodeValue);
But that did not return the values.
Any idea on how best to do this? I feel like I am very close to having this working! Thanks!
You can use $.parseXML, and then loop over the elements with .each().
var $xml = $.parseXML(xml);
$("#response", xml).children().each(function(i, e) {
var field = e.tagName;
var value = e.innerHTML;
$("#" + field).val(value);
});
You're on the right track. What it comes down to is that when you parse an XML file, the parser doesn't care what the fields are, it'll parse it as it sees it. You would basically have to tell the script to pull certain tags with certain text. As far as I know, this is best done using the .tagName property and the tag's value and storing it in an object.
var data={}
$(this).children().each(function() {
data[this.tagName]=$(this).text();
})
You can see how this would work here:
http://jsfiddle.net/dpK7x/1/

How to find the URL of an external site's Javascript submit

I will do my best to try to explain this.
I am scraping a website for it's elements to then output in a different format. The problem that I am experiencing is the way that this site directs the user throughout the site is through a Javascript redirect.
When checking the 'a href' tag, this is the Javascript that shows up
javascript:doParamSubmit(2100, document.forms['studentFilteredListForm'], 'SSC000001MU9lI')
The SSC000001MU9lI changes for each element that it redirects to.
Is it possible to find a URL using this Javascript, so that I can reach the HTML page externally?
EDIT: Here is the doParamSubmit and doSubmit classes:
function doParamSubmit(event, form, parameter) {
form.userParam.value = parameter;
doSubmit(event, form);
}
function doSubmit(event, form)
{
// Make sure if something fails that the form can be resubmitted
try
{
// If this form has not been submitted yet... (except for IE)
if (allowSubmit == true && form != null && (submitted == false || isInternetExplorer6() || isInternetExplorer7()))
{
submitted = true;
form.userEvent.value = event;
// Fix for IE bug in which userEvent becomes a property array.
if (form.userEvent.length)
{
form.userEvent[0].value = event;
}
// Disable the form so the user can't accidentally resubmit the page
// (NOTE: this doesn't disable links (e.g. <a href="javascript:...">)
disableForm(form);
// If there is a populate form function, call it. If there are spell check fields on the
// page, populateForm is used to set hidden field values.
if (this.populateForm)
{
populateForm();
}
saveScrollCoordinates();
// resetSessionTimeout();
try
{
form.submit();
}
catch(e)
{
// Exceptions thrown here are only caused by canceling the submit in onbeforeunload, so ignore.
submitted = false;
}
}
if (allowSubmit == false)
{
alert(grabResource("message.pageLoading"));
}
}
catch(e)
{
submitted = false;
throw e;
}
}
I see 2 approaches.
You use a javascript enabled browser such as http://nrabinowitz.github.io/pjscrape/. I am not sure if you intend to just follow the links or instead grab the URL for some other use so your mileage may vary.
Find the doParamSumit() function in their page/scripts and analyze it to understand how it gets the URL - the one you have as an example looks like it grabs the action from a form perhaps? Once you know how the function work you might be able to harness that info in your scraping by using some regex to find URLs that match the doParamSubmit pattern and going from there. It's hard to say without seeing the function itself as well as the other links like it though.
Regardless of which method you choose I would begin by understanding the function - look for it in the code or loaded js files (you can also you things like javascript debuggers on most browsers to help you find it) and see what happens - it might be super obvious.
Also keep in mind that this might be a POST for a form - in which case the result of you following that link may not work if it expects valid form data.
Edit I see that you posted the function. It simply submits the form listed in the second parameter i.e. 'studentFilteredListForm'. While I don't think your scraping will go to far chasing forms you can still get the URL either with javascript if your scraper lets you (something like $('form[name=studentFilteredListForm]').attr('action') or using whatever language your are using for the scraper i.e. find the form and extract the action url (remembering that if there is no action it is probably posting back to the current URL)
But again... you might first manually get the URL of the form and see where that gets you. You might just get a page with form errors :)

submitting form through javascript and passing a variable with it

I want to submit a form and add a javascript variable with it. I tried using AJAX but that didn't work properly because the form is cut in two parts on the same page. I'm now using a <button onclick='submit_form()'>send</button> which calls on the following function:
function submit_form()
{
document.getElementById("form2").submit();
}
however I need to pass on a javascript variable current_score I have it declared and it has a value I just don't know how to add this to my submit function I tried using a return within the function itself and writing a function for it but neither worked :) help and hints are greatly appreciated.
The idea is that people receive a score fill a form and send it to a database, The ajax script part was to try and pass the values on to the next page that will submit the data
Your question is not very clear. The simple way would be to append a get parameter to the URL you are requesting. The following example will append a hidden input element to your form:
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "theName";
hidden.value = current_score;
var f = document.getElementById("form2");
f.appendChild(hidden);
f.submit();
You could store the information in window.variable also

Jquery validation before form submits to php

I have tried and tried with this and don't seem to be getting anywhere, so thought I would put it out there. I have a form full of data provided by the user that I have thus far been able to validate with js/jQuery without problem before sending it to php for further processing. I am achieving this like so:
form.submit(function(){
if(validateUserName() & validateEmail1() & validateEmail2() & validatePass1() & validatePass2() & acceptTerms()){
return true;
} else {
return false;
}
});
The form itself uses the following attributes:
<form id="signup" action="registration.php" method="post">
The problem function is acceptTerms(), which simply has to check that a checkbox is selected does not seem to work as it should (or as the rest of the validation functions do).
var termscons = $('input:checkbox[name=termscons]');
termscons.change(acceptTerms);
function acceptTerms(){
if($(termscons).is(':checked')) {
termsconsInfo.text("");
return true;
} else {
termsconsInfo.text("In order to join, you must accept these terms and conditions.");
return false;
}
}
I have integrated the termscons.change listener and termsconsInfo.text(""); to ensure that my selectors are pointing at the right thing, and that the function is being fired correctly (which it appears to, by changing the termsconsInfo.text when its state changes). When I try to submit the form however it appears to return false, since it does not submit. It should in fact be returning true, and posting my form over to my php script.
Am I going about this the right way? Is there something I have been missing when dealing with a checkbox as opposed to a textinput?
Please excuse my ignorance, this is all still very new to me.
First problem is that you are using & in your if statement. It needs to be &&.
Second problem is with acceptTerms (as you guessed):
var termscons = $('input:checkbox[name=termscons]');
termscons.change(acceptTerms);
function acceptTerms(){
if(termscons.is(':checked')) { // <-- termscons is already a jQuery object
termsconsInfo.text("");
return true;
} else {
termsconsInfo.text("In order to join, you must accept these terms and conditions.");
return false;
}
}
There might be more, but that is what I see for now.
i say forget reinventing the wheel and use something already tested for instance jQuery validate

Categories

Resources