Javascript filled field value $_POST's NULL? - php

I've got a form that I'd like to fill with Javascript. It works!
But when I submit the form, it doesn't validate, and it says that field is null.
If I fill in the form manually, it works just fine?
The form in question is here
EDIT
Here's the JS for the form
$('#old').keyup(function () {
if(this.value > 49){
$('#new').val(this.value - 49);
$('#new').attr('disabled', 'disabled');
} else {
$('#new').val('0');
$('#new').removeAttr('disabled');
}
});

Disabled fields don't get submitted by the browser. If you're looking for their values in PHP, they won't exist.

In addition to Francois' answer, you can use readonly instead of disabled.

Related

How do I find out if an input with a certain name exists in a certain form?

I have an onclick event on all forms on the page:
$('form[method="post"]').click(function() {
if($('textarea[name="serialized_data"]').length > 0) {
alert("serialize_data already exists in this form!");
return false;
}
var data=$(this).serialize();
$(this).append('<textarea name="serialized_data">'+(data)+'</textarea>');
});
If you press a submitbutton and then on the target page press back in the browser, then this alert comes up.
But this solution stops on all forms.
How can I apply the alert only on the form that submitbutton was already pressed?
If you wonder why I input all data in that textarea, that is another question: compact all form-data with javascript
You're selecting all textareas anywhere, instead of those within the clicked form. Try this:
$('textarea[name="serialized_data"]', this)
That restricts the selector to the context of this, which is the form.

Changing the value of the checkboxes via jQuery

I have a few checkboxes in my form and I need to change their value when the checkbox is checked.
For example this is one of the checkboxes:
<input type="checkbox" name="drink" value=""/>
I know .val() can change it but I wasn't able to do this with if statement.
I appreciate your answer in advance.
What you are seeking is actually very meaningless. See, when a form is submitted, only the checked checkboxes actually send values, so it makes no sense to change the value especially for the unchecked checkbox.
Better Solution
You should instead give it the "checked" value, and keep it that way, that will cause it to submit correctly even without changing the values.
You can add a click event listener on the checkbox:
$('input[name="drink"]').click(function() { // when click on it
if ($(this).attr('checked')) { // if the checkbox is checked
$(this).val("value #1"); // change the value
} else { // otherwise if is unchecked
$(this).val("value #2"); // change the value
}
});
// attach an onchange handler to all checkboxes on the page
$("input[type='checkbox']").change(function() {
// or if($(this).prop("checked")) {
if(this.checked) {
$(this).val("value for checked");
} else {
$(this).val("value for unchecked");
}
});
The onchange event is the one you should be interested when it comes to checkboxes, as it fires whenever you change the checked state of it.
The checked property determines whether or not the checkbox has been checked.
The .val() method allows you to conveniently read/write element values.

Disabling submit button stops form from being submitted PHP / Javascript

I think I got a classic problem but I was not able to find a working solution so far.
I have got a form , the user clicks "Send" and everything works fine using a PRG pattern and doing both client-side and server-side validation.
The problem arises when any user (let's assume he entered valid inputs) clicks more then once quickly before the server script ends its execution...
I do not get any duplicated entry because I took care of that but the browser does not go to my "thanks for submitting page".
Instead it re-submits the same page with the same values and what I get are the custom errors I set to warn the user he is trying to enter details already stored in the database. The details sent in the first place are all in the database but the user has no chance to know that.
I tried to disable the submit button on a submit event using jQuery but in that case the data are not submitted.
HTML
<div id="send-button-container">
<input id="send-emails" type="submit" name="send_emails" value="Send"/>
</div>
jQuery
$(document).ready(function(){
$('#mail-form').submit(function(){
$('#send-emails').attr('disabled','disabled');
});
});
I am wondering if I can force a submission using Javascript after disabling the button and also how to deal with UAs with Javascript disabled
Thanks in advance
Depending on server-side language, the submit button being disabled could cause problems. This is because disabled elements are not POSTed to the server. Languages like ASP.NET require the button value to be submitted so it knows what event handler to fire. What I usually do is hide the submit button, and insert a disabled dummy button after it, which appears identical to the user. Then in your onsubmit handler, you can return false and submit the form programmatically...
$('#mail-form').submit(function(){
var btn = $('#send-emails');
var disBtn = $("<input type='button'/>").val(btn.val()).attr("disabled", "disabled");
btn.hide().after(disBtn);
this.submit();
return false;
});
Contradictory to the other up-voted answers, please note that you do not need to explicitly return true from your submit handler for natural form submission: http://jsfiddle.net/XcS5L/3/
I assume this means you are depending on the value of the submit button to service the request? That is you are checking
$_REQUEST['send_emails'] == 'Send';
This is not good practice. You should never depend on the value of the submit button because that is the just what is displayed to the user. Instead, you should add a hidden input that contains the event you want to fire. After the form is submitted, you don't need to care what the value of the submit button is and you can disable it. All other non-disabled data in the form is still submitted.
You can indeed force the submission after disabling the button.
$(function () {
$("#mail-form").submit(function () {
$("#send-emails").attr('disabled', 'disabled');
window.location = '?' + $("#mail-form").serialize() + '&send_mails=Send';
return false;
});
});
Server side set a $_SESSION variable that keeps track of the last time they made a submission and block submissions within a certain time.
<?php
session_start();
if (isset($_REQUEST['send_emails'])) {
if (isset($_SESSION['mail_sent'])
&& strtotime($_SESSION['mail_sent']) < strtotime('5 seconds ago')
) {
redirect_to_thanks();
}
do_post();
}
function do_post() {
if (do_validate()) {
$_SESSION['mail_sent'] = time();
redirect_to_thanks();
}
else {
yell_at_user_a_lot();
}
}
?>
You have to return true; You could try this if u want a simple button to submit the form.
$(function(){
$('#submitID').one('click',function(){
$('#formTobeSubmitted').submit();
$(this).attr('disabled','disabled');
})
});
On server side, generate a random number into each form, store the number when the form is submitted, and discard the submit if that number has already been stored earlier. When the user has disabled javascript, this is the best you can do. (Concurrency issues can be tricky as the two identical requests are handled at the same time - make sure you use some sort of locking mechanism, such as a table with a unique field or the flock() command in PHP.)
On browser side, just set a flag when the form is submitted, and discard all later submits:
$('#mail-form').submit(function() {
if ($(this).data('submitted') {
return false;
} else {
$(this).data('submitted', true).addClass('submitted');
}
});
You can use the submitted class to make the buttons gray or something. This has a few advantages to simply disabling them; Josh already said one. Another is that Firefox likes to remember disabled states when you hit refresh, which can cause your users getting stuck in certain situations.

Javascript validation for radio button

I am doing newsletter subscription.I have 2radio buttons-subscribe and unsubscibe and a submit button.But when I click on submit button,ajax function gets called for subscription.Now i want to do validation.I have written a javascript validation for radio buttons as below:
function validate_radio()
{
var radio_choice = false;
var radio_val = document.newsletterform.subscribe.length;
for (counter = 0; counter < radio_val; counter++)
{
if (document.newsletterform.subscribe[counter].checked)
radio_choice = true;
}
if (!radio_choice)
{
document.getElementById("mandatory").innerHTML="Select Subscribe/Unsubscribe";
return false;
}
}
But now I am getting the validate message but at the same time i am getting subscribed.
tell me a way so that i can stop the subscription being done if the function returns false.
I am calling the function as follows:
Sounds like your form isn't stopping when it should be. I assume you have something like
<form onsubmit="validate_radio()">...</form>
Since your validate_radio() function returns false on failure, you just need to modify your form to fail if the validation does:
<form onsubmit="return validate_radio()">...</form>
So the form will halt if validation fails.
For what it's worth, I think that it's not good for a form to include radio buttons that don't start off with one being selected. Young people don't remember old radios, or being yelled at for messing around with the buttons to get them all to pop out. Radio buttons are called "radio buttons" because one of them must always be selected. It's friendlier for your users to have the buttons initialized to a good default setting.

JQuery help with checkboxes and their values

I am very new to javascript and JQuery but I managed to get my first ajax script almost working 100%. Maybe today will be my lucky day and I can finish this up. :)
Let me give you guys a sample of each file so you know what is what. I believe that my last try at figuring this out was not successful because I was confusing these files. They are all js and have the exact same syntax.
What I have are 2 javascript files. One is called ajax.js and has the folling syntax. it calls ajax.php.
$("#admEmpID").bind("change", function(e){
$.getJSON("ajax.php?e=" + $("#admEmpID").val(),
function(data)
{
$.each(data, function(i,item)
{
if (item.field == "admEmpStatus")
{
// ?? radio buttons
}
............. etc
The next file I have is this script and is called admEmp.js. I think that this one is for my form validation.
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admEmpBtn").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var admEmpID = $("input#admEmpID").val();
var admEmpStatus = $("input[name='admEmpStatus']:checked").val();
$.ajax({
type: "POST",...............etc.
What I would like to do is toggle my checkboxes according to the database results. If the result from the database is = 1 then the checkbox should be checked otherwise it should be unchecked.
These scripts that I have in place now will populate my textboxes from the values in the database so for someone like myself who has no idea what is happening with JQuery and its innerworkings, it is only natural for me to assume that the checkboxes will also be filled with the on/off values. Maybe I am incorrect. The last time I posted on SO looking for help, a guy mentioned that I needed to toggle the results with server side code. Is this correct or will JQuery do it for me?
I also have radio buttons in addition to the checkboxes that I need to show the values for as well. Just as a side note, the checkboxes are not grouped; they each have their own value.
Thanks for any help you guys can provide.
OK. "dz" said that I should put ('#admCustRptDly').attr('checked', true); into my script to see if that will allow me to see the checked attribute but it doesn't. The database has a 0 for that checkbox so I sould be seeing no checkmark. I put that into the ajax.js file. Here is what it looks like now.
else if (item.field == "admCustRptDly" && item.value == "1")
{
// $("checkbox#admCustRptDly").attr("checked", "checked");
$('#admCustRptDly').attr('checked', true);
}
Here is what I did that makes me think that I may be making some progress. I put an alert inside of the condition and I do NOT get an alert. If I go to a customer that does have the db value set to 1, then I do get the alert. That's more than I was getting before. But again, I am still seeing the checkmark even though the data in the db = '0'
Checkboxes behave a little differently than other input fields. When you have <input type="text" name="field1" value="foo" /> for example, the text field is automatically populated with "foo".
However, if you have <input type="checkbox" name="field2" value="1" />, the checkbox doesn't have anything to populate. This is because the checkbox has a special "checked" attribute that determines whether or not it is checked by default. As such, it's very possible your script that populates your textboxes are putting in the correct value for the checkbox, but are not setting the checked attribute.
To do so with jQuery, you can do $('#checkboxid').attr('checked', true);.
If I understand correctly, you have a form that is updated asynchronously via an Ajax call when you change the value in the #admEmpID field (first js file).
The second js file contains code to post changes you made to the form back to the server. I don't think it's for form validation (at least not the part you're showing).
But I'm not sure what the problem is. The first js file gets data from the server when you change some text field (#admEmpId). Is that data not shown correctly? You mention that textboxes are filled with the correct data. Are the checkboxes and radiobuttons not selected when they should be? In that case, you must first make sure you understand what data is returned from the server (contained in the data variable in the first js file). Then you must verify that the script addresses the right elements on your page to be updated.
You may just need another else if clause in your javascript for the case when you want to uncheck a box:
else if (item.field == "admCustRptDly" && item.value == "0")
{
$('#admCustRptDly').attr('checked', false);
}
You could, however, simplify both cases into a single statement like so:
else if (item.field == "admCustRptDly")
{
$('#admCustRptDly').attr('checked', ((item.value == "1") ? true : false));
}

Categories