I'm new to work Javascript & ajax. I am creating a basic form & saving the values in the Mysql database. After hitting the submit button only first radio button value is getting saved in Database. Can anyone help me out? Here is my HTML Code :
<form>
<div class="form-group">
<div class="form-group">
<label>Email:</label>
<input type="email" class="from-control" name="Name">
</div>
<label class="form-check-label">Gender</label>
<div class="form-check-inline">
<input type="radio" class="form-check-input" name="Sex" id="Sex" value="Male" />Male
<input type=radio class="form-check-input" name="Sex" id="Sex" value="Female" /> Female
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" id="btn_submit">Submit</button>
<button class="btn btn-seconday" type="button" id="btn_cancel">Cancel</button>
</div>
</div>
</form>
And my Javascript code:
<script type="text/javascript">
$(document).ready(function () {
$('#btn_save').on('click',function() {
var Email = $('#Email').val();
var Sex = $('#Sex').val();
$.ajax({
type : "POST",
url : "https://localhost/newCrud/test/save",
dataType : "JSON",
data: {Email:Email, Sex:Sex},
success : function (data) {
$('[name = "Email"]').val("");
$('[name = "Sex"]').val("");
}
});
return true;
});
});
</script>
The Database structure
Saved data from form submission

Kindly help me with my problem guys, I did my fair amount of research & couldn't find solution to my problem. Thank you for you suggestions.
Seems like a data model issue.
You are retrieving the value from your html wherever Name equals "Sex". You have two inputs with the Name equaling "Sex". Jquery will pick the first input with the name "Sex" from the DOM. Thus you are always updating the sex to whatever the value of the first input is with the Name "sex".
That's your problem.
We can give you a proper solution if we see what your table looks like for the db instance you are inserting into.
Ids must always be unique. When you do var Sex = $('#Sex').val(); You will only ever get the first result, as it appears first in the DOM. There are plenty of different ways, but an easy option to get the values would like like...
Note: in my example female is already checked.
function getRadioValue(name) {
var inputs = Array.from(document.getElementsByName(name));
checkedRadio = inputs.filter(x => x.checked);
if (checkedRadio.length) {
return checkedRadio[0].value
}
}
console.log(getRadioValue("Sex"));
<div class="form-check-inline">
<input type="radio" class="form-check-input" name="Sex" value="Male" />Male
<input type=radio class="form-check-input" name="Sex" value="Female" checked /> Female
</div>
By default one radio button should be selected.
id attribute of HTML should be unique. In that case, you'll always get the first value of corresponding id.
Easier way to solve your problem:
var Sex = $('input[name="Sex"]:checked').val();