AJAX POST not sending all data - javascript

I have the following HTML code within a form and the top one (policy) sends in post but the second one does not (mfa). I'm lost at why this is happening, any ideas?
<label class="switch switch-flat">
<input class="switch-input" type="checkbox" id="policy" method="post" name="policy" <?php if($row['policy'] === '1') echo 'checked="checked"';?> />
<span class="switch-label" data-on="Yes" data-off="No"></span>
<span class="switch-handle"></span>
</label>
<label for="policy">Does the vendor organization have a written Information Security policy?</label>
</td>
</tr>
<tr>
<td>
<div class="col-md-12">
<label class="switch switch-flat">
<input class="switch-input" type="checkbox" name="mfa" id="mfa" method="post" <?php if($row['mfa'] === '1') echo 'checked="checked"';?> />
<span class="switch-label" data-on="Yes" data-off="No"></span>
<span class="switch-handle"></span>
</label>
<label for="mfa">Do they support and utilize multi-factor authentication?</label>
</td>
Here's my ajax to send the post data. When I browse in the Dev tools for headers being sent I see a lot of the other HTML names going but most of the ones listed as toggle checkboxes aren't being sent except for the top one 'policy'.
<script type='text/javascript'>
/* attach a submit handler to the form */
$('#update').submit(function(e){
e.preventDefault();
$.ajax({
url:'updateVendor.php',
type:'post',
data:$('#update').serialize(),
success:function(){
//whatever you wanna do after the form is successfully submitted
}
});
});
</script>

A checkbox is only considered to have a value when it is checked. Otherwise, it is not included in the submitted form data.
From the MDN website:
Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all. If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value, generated by JavaScript perhaps.
A trick to circumvent this limitation is to include a hidden input with a default value. E.g.
<input name="mfa" type="hidden" value="0">
<input name="mfa" type="checkbox" value="1">
With this approach, a value for mfa will always be submitted with the form data.

Related

Value from a dynamic JS computed value returns NULL when php gets the input value [duplicate]

I have some disabled inputs in a form and I want to send them to a server, but Chrome excludes them from the request.
Is there any workaround for this without adding a hidden field?
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input type="textbox" name="Percentage" value="100" disabled="disabled" />
</form>
Elements with the disabled attribute are not submitted or you can say their values are not posted (see the second bullet point under Step 3 in the HTML 5 spec for building the form data set).
I.e.,
<input type="textbox" name="Percentage" value="100" disabled="disabled" />
FYI, per 17.12.1 in the HTML 4 spec:
Disabled controls do not receive focus.
Disabled controls are skipped in tabbing navigation.
Disabled controls cannot be successfully posted.
You can use readonly attribute in your case, by doing this you will be able to post your field's data.
I.e.,
<input type="textbox" name="Percentage" value="100" readonly="readonly" />
FYI, per 17.12.2 in the HTML 4 spec:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements are successfully posted.
Using Jquery and sending the data with ajax, you can solve your problem:
<script>
$('#form_id').submit(function() {
$("#input_disabled_id").prop('disabled', false);
//Rest of code
})
</script>
To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.
<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
<!-- Re-enable all input elements on submit so they are all posted,
even if currently disabled. -->
<!-- form content with input elements -->
</form>
If you prefer jQuery:
<form onsubmit="$(this).find('input').prop('disabled', false)">
<!-- Re-enable all input elements on submit so they are all posted,
even if currently disabled. -->
<!-- form content with input elements -->
</form>
For ASP.NET MVC C# Razor, you add the submit handler like this:
using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
// Re-enable all input elements on submit so they are all posted, even if currently disabled.
new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
<!-- form content with input elements -->
}
If you absolutely have to have the field disabled and pass the data you could use a javascript to input the same data into a hidden field (or just set the hidden field too). This would allow you to have it disabled but still post the data even though you'd be posting to another page.
I'm updating this answer since is very useful. Just add readonly to the input.
So the form will be:
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<input type="textbox" name="Percentage" value="100" readonly/>
</form>
Semantically this feels like the correct behaviour
I'd be asking myself "Why do I need to submit this value?"
If you have a disabled input on a form, then presumably you do not want the user changing the value directly
Any value that is displayed in a disabled input should either be
output from a value on the server that produced the form, or
if the form is dynamic, be calculable from the other inputs on the form
Assuming that the server processing the form is the same as the server serving it, all the information to reproduce the values of the disabled inputs should be available at processing
In fact, to preserve data integrity - even if the value of the disabled input was sent to the processing server, you should really be validating it. This validation would require the same level of information as you would need to reproduce the values anyway!
I'd almost argue that read-only inputs shouldn't be sent in the request either
Happy to be corrected, but all the use cases I can think of where read-only/disabled inputs need to be submitted are really just styling issues in disguise
I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.
<input readonly style="color: Grey; opacity: 1; ">
Simple workaround - just use hidden field as placeholder for select, checkbox and radio.
From this code to -
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input type="textbox" name="Percentage" value="100" disabled="disabled" />
<select name="gender" disabled="disabled">
<option value="male">Male</option>
<option value="female" selected>Female</option>
</select>
</form>
that code -
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<input type="textbox" value="100" readonly />
<input type="hidden" name="gender" value="female" />
<select name="gender" disabled="disabled">
<option value="male">Male</option>
<option value="female" selected>Female</option>
</select>
</form>
In addition to Tom Blodget's response, you may simply add #HtmlBeginForm as the form action, like this:
<form id="form" method="post" action="#Html.BeginForm("action", "controller", FormMethod.Post, new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" })"
Define Colors With RGBA Values
Add the Following code under style
<!DOCTYPE html>
<html>
<head>
<style>
#p7 {background-color:rgba(215,215,215,1);}
</style>
</head>
<body>
Disabled Grey none tranparent
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input id="p7" type="textbox" name="Percentage" value="100" readonly="readonly"" />
</form>
result
I had exactly the same problem, but did not work for me, because I have select HTML element, and it's read-only state allowed to change its value.
So I used select in one condition and input in another:
<% If IsEditWizard Then %>
<%For Each item In GetCompaniesByCompanyType("ResponsibleEntity")%>
<% If item.CompanyCode.EqualsIgnoreCase(prCompany.GetAsString("LinkedCompany")) Then %>
<input type="text" value="<%: item.CompanyName %>" tabindex="3" size="12" maxlength="12" readonly="readonly" />
<input type="hidden" id="LinkedCompany" name="LinkedCompany" value="<%:item.CompanyCode %>" tabindex="3" size="12" maxlength="12" />
<%End If %>
<%Next %>
<%Else %>
<select id="LinkedCompany" name="LinkedCompany" class="w-auto" <%= If(IsEditWizard, "disabled", "") %>>
<option value="">Please Select</option>
<%For Each item In GetCompaniesByCompanyType("ResponsibleEntity")%>
<option value="<%:item.CompanyCode %>" <%: IIf(item.CompanyCode.EqualsIgnoreCase(prCompany.GetAsString("LinkedCompany")), "selected", String.Empty) %>><%: item.CompanyName %></option>
<%Next %>
</select>
<%End If %>
use
<input type="textbox" name="" value="100" disabled/>
or
<input type="textbox" name="" value="100" readonly/>
if your are using framework like PHP Laravel, element without name attribute will read as unset
<input type="textbox" value="100" disabled/>
You can totally avoid disabling, it is painful since html form format won't send anything related to <p> or some other label.
So you can instead put regular
<input text tag just before you have `/>
add this
readonly="readonly"
It wouldn't disable your text but wouldn't change by user so it work like <p> and will send value through form. Just remove border if you would like to make it more like <p> tag

How to retain use selected option in radio buttons?

I have a text form that uses a radio button of two options. For example, the 'exact match' is checked by default. However, whenever the 'submit' is clicked, the option reverts back to the default section, which is undesired. I want to retain the radio option currently selected by users, not the default one.
<form class="search" action="{{ url_for('nlp.wbkg') }}" method="post">
<input name="query" type="text" id="query" value="{{query}}" autocomplete="on" required>
<button type="submit"><i class="fa fa-search"></i></button>
<div>
</div>
<div>
<input type="radio" name="options" id="exact" value="exact" checked="checked"> Exact match </input>
<input type="radio" name="options" id="fuzzy" value="fuzzy"> Fuzzy Match </input>
</div>
</form>
How to achieve that effect?
EDIT: add my server-side code in flask:
#bp.route('/wbkg', methods=('GET', 'POST'))
def wbkg():
if request.method == 'POST':
query = request.form['query']
search_type = request.form['options']
results, terms = search(query, search_type)
return render_template('nlp/wbkg.html', items=results, terms=terms, query=query)
flash(error)
return render_template('nlp/wbkg.html')
How to handle it in server side?
Since you are wrapping your element in a form tag you should be sure to have your submit handler run event.preventDefault() to prevent the resetting of the form after the submit is fired. You may be witnessing the reset of the form after the API call was sent. You can confirm this by looking at your REQ body to see if the data sent is correct.

Checkbox included into form from child view by ajax is not detected by post method

I made ajax live search in my form and now paginated data/html comes from child view with ajax and js help. Search returns a checkbox, so I mark this checkbox and click submit/post and in dumpdata I cannot see this selected checkbox. Page inspection shows such code after ajax search is performed:
<tr>
<td>
<div class="form-chceck">
<input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="56">
<label class="form-check-label" for="exampleRadios1">
56
</label>
</div>
</tr>
</td>
If I put something like that directly into my blade form view instead of:
#csrf
<tbody>
#include('projects/projects_child')
</tbody>
then it works fine.
Ajax:
$.ajax({
url:"/projects/projects/fetch_data?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query,
success:function(data)
{
$('tbody').html('');
$('tbody').html(data);
}
})
What could be the issue?
Adding a checkbox value isn't the same as making a checkbox as checked. What you did just means when it's checked it's value will be 56. I believe this is what you're looking for:
<input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="56" checked>
You can wrap that attribute in an #if or something if you need to in your blade template.

How to determine which radio button is selected in second page using session

I have two radio buttons and the session to store which button is selected, which I want to access in my second page.
On selection of each radio button, there will be different fields to be displayed in second page which is modal.
For example, if user selects first one (e.g.: date and time filled should be hidden) on second it should display. How to do this?
<td>
<label class="radio-inline"><input type="radio" name="reason" value="1">Executed</label>
</td>
<td>
<label class="radio-inline"><input type="radio" name="reason" value="2">Expired</label>
</td>
<td>
<label class="radio-inline"><input type="radio" name="reason" value="3">Another Option</label>
</td>
and PHP code
//$reason = $_REQUEST['reason']; OR
$reason=$_POST['reason'];
this is your form data and you can change action if you want . suppose first submit form in same page2 then use this code
<form method="post" action="page2.php">
<input type="radio" name="reason" value="1"/>Reason1
<input type="radio" name="reason" value="2"/>Reason2
<input type="radio" name="reason" value="3"/>Reason3
<input type="submit" value="submit"/>
</form>
in second page this is code
and you want to use this value any place then use this code in your any place from project
<?php
session_start();
$reason = $_SESSION['reason'];
echo $reason;
?>

Disable submit button after submit and page refresh

What i want is pretty simple, i have a button that submits a value to my database once clicked, what i need is to diable the button parmanently after value has been submited, i have searched and the codes i have seen all enable the button when the page refreshes.. please can someone help me out?
My form and button code as follows:
<form action="<?php echo $editFormAction; ?>" method="POST" name="Status2" id="Status2" onSubmit="return confirm('Are you sure you want to submit?');">
<input name="Confirm2" type="checkbox" id="Confirm2" value="Confirmed" checked="CHECKED" style="display:none;">
<label for="Confirm2"></label>
<input name="UpdateButton3" type="submit" class="art-button" id="UpdateButton3" value="Confirm"/>
<input name="UserIDHiddenField4" type="hidden" id="UserIDHiddenField4" value="<?php echo $row_User['UserID']; ?>">
<input name="Purge2" type="checkbox" id="Purge2" value="You Will Be Rematched Soon!" checked="CHECKED" style="display:none;">
<label for="Purge2"></label>
<input type="hidden" name="MM_update" value="Status2">
</form>
First of all if you submit it, this has nothing to do with javascript. Save this in your database as #georoot says. Then when you submit, save a value in the database. If that value is set, you can disable the button by just HTML:
<input type="submit" <?php if($valueFromDatabase==1){ ?> disabled <?php } ?> >
Best solution could be to set a cookie on client system and/or get user IP and save it into your database, but you should keep in mind, non of them are permanent ! The IP can be changed and the cookie can be removed ! But you can use both cookie and IP check.
Then for each page load, just check if cookie exist (compare the value with ur database value) and/or client IP is already exist in database.
Or if you know who is on the page (if it's a logged user) just add a field in your database and set value = 1 or = 0 and check the field each time it's loaded for same field and for same user.
I wouldn't recommend to use IP check without cookies ! Because it can change frequency !

Categories

Resources