No matter what option is chosen, this code will always submit the second option to PHP.
Here is my form:
<div class="modal">
<div class="modalContent">
<div class="modalHeader">
<p>Add an income / expense</p>
<span class="closeBtn" onclick="closeit()">×</span>
</div>
<form class="insertData" action="insert.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="category">Category</label>
<select name="category" required>
<option value="food">Food</option>
<option value="bills">Bills</option>
<option value="rent">Rent</option>
</select>
<label for="amount">Amount</label>
<div class="radios">
<input type="radio" name="ie" value="income"><p>Income</p>
<input type="radio" name="ie" value="expense"><p>Expense</p>
</div>
<input type="number" name="amount" required>
<label for="description">Description (optional)</label>
<textarea type="text" name="description"></textarea>
<input id="start" type="text" name="start" value="" required style="display:none;">
<input id="end" type="text" name="end" value="" required style="display:none;">
<input class='submitBtn' type="submit" name="" value="Submit">
</form>
</div>
</div>
Here is the PHP (just echoing for debugging purposes right now):
if (isset($_POST['name'])) {
echo htmlspecialchars($_POST['ie']);
}
The data is going in via AJAX here (using FullCalendar)
select: function (start, end) {
document.getElementsByClassName('modal')[0].style.display = 'block';
document.getElementById('start').value = $.fullCalendar.formatDate(start,
"Y-MM-DD HH:mm:ss");
document.getElementById('end').value = $.fullCalendar.formatDate(end,
"Y-MM-DD HH:mm:ss");
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});
},
No matter what option is chosen it will always submit 'expense'.
If I swap them around on the form then it will always submit 'income', so it seems to be always the last option is being submitted.
This error occurs because you loop all element has name attribute, and get the value. Including radio button. If you want to get selected radio button you must add if, for check if radio button has checked.
You can use code below, this code simpleer then you must check radio button:
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
$.ajax({
url: url,
type: type,
data: $('form.insertData').serialize(),
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});
Related
I having 3 textbox and I want to send value enter over there to controller method
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">
#Html.ActionLink("Send", "MethodNameInController", "ColtrollerName", new { id= $('#id').val(),
id1= $('#id1').val(), id2= $('#id2').val()})
and in controller
public ActionResult MethodNameInController(int id, string id1, string id2)
{
//some text here
}
but it's sending null value
If you want to stay on the same view or redirect to another url after, instead of using #Html.ActionLink() try passing the values to the controller using an ajax call.
function submitAjax(){
//purely for readability
var id = $('#id').val();
var id1 = $('#id1').val();
var id2 = $('#id2').val();
//ajax call
$.ajax({
url: "/ControllerName/MethodNameInController",
data: { id: id, id1: id1, id2: id2 },
success: function (result) {
//handle something here
}
});
};
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">
<button type="button" onclick="submitAjax()">submit</button>
If the method does some processing and then returns you to a different view, you could do a form submit.
function submitForm(){
var $form = $("#idForm");
//optional validation
$form.submit();
};
<form id="idForm" class="form-horizontal" asp-controller="ControllerName" asp-action="MethodNameInController" >
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">
<!-- type="button" prevents the from from submitting so you can do validation checks in the js -->
<button type="button" onclick="submitForm()">submit</button>
</form>
I got the solution using ajax just want to know is there any direct solution
$(function () {
$('#receipt').unbind('click');
$('#receipt').on('click', function () {
$.ajax({
url: "/Controller/Method",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
fromDate: $("#fromDate").val(),
toDate: $("#toDate").val(),
id: $("#id").val()
}),
async: false
});
});
});
I use codeigniter and jquery
By example if input#1 is checked, i have to get the value of input#menu-1
if input#2 is checked i get the value of input#menu-2 ...
even if all are checked ,
what i tried :
<form id="form">
<h2 class="text-uppercase font-weight-light">votre choix : </h2>
<div class="flex-row">
<input type="checkbox" id="1">
<label for="menu-1">item 1<span class="font-weight-bold">($ 500 )</span> x
</label>
<input id="menu-1" type="number" class="min" maxlength="2" value="1">
</div>
<div class="flex-row">
<input type="checkbox" id="2">
<label for="menu-2">item 2<span class="font-weight-bold">(2500 FCFA)</span> x
</label>
<input id="menu-2" type="number" class="min" maxlength="2" value="0">
</div>
<button id="next-1" type="submit" class="btn border border-secondary p-2">COMMANDER</button>
</form>
i have tried :
$('#next-1').click(function (e) {
e.preventDefault();
var form = $("#form").serialize();
$.ajax({
url: '<?php echo base_url("index.php/user/process") ?>'
method: 'POST',
data: form,
dataType: 'json',
success: function (reponse) {
}
});
});
my controller :
public function process()
{
if ($this->input->is_ajax_request()) {
$data = $this->input->post();
echo json_encode($data);
}
}
but i don't get values so it doesn't work
Because you are missing name attribute in input. Try this
<input id="menu-1" type="number" class="min" maxlength="2" value="1" name="menu-1"> // check here name attribute at last.
form serialize take value from name attribute.
in your javascript
$("#form").click(function (e) {
let form = $(this);
//for data filtering
var serializedReturn = form.find('input[name!=menu-1]').serialize(); // here menu-1 be removed.
console.log(serializedReturn, 'value');
e.preventDefault();
});
I have a simple modal popup that edits an item retrieved from the back end. The for has several input and select controls. The input form controls work properly but the select controls are not pre-populated as intended.
The basic architecture of my functions as follows:
function BootboxEditItem(id) {
$.ajax({
// Load back end data
})
.done(function(data) {
var itemData = data;
$.ajax({
// Load form template for modal
url: '/modal/item/edit-item.html',
......
})
.success: function (data) ({
var box = bootbox.confirm({
// Set up bootbox buttons;
},
callback: function(result){
// Post edited data back to the server
}
)};
box.on("shown.bs.modal", function(e) {
// Populate the modal here using data from the backend.
// This is where the problem lies!
})
box.modal("show");
});
}
Below is the full JavaScript code:
function BootboxEditItem(id) {
var itemDao = '';
$.ajax({
type: "GET",
contentType: "application/json",
url: "/api/item/edit/" + id,
dataType: "json",
cache: false
})
.done(function (data) {
itemDao = data;
$.ajax({
type: "GET",
url: '/modal/item/item-edit-form.html',
success: function (data) {
console.log(itemDao);
var box = bootbox.confirm({
message: data,
title: "Edit Item: [" + itemDao.item.sysId + "]",
buttons: {
cancel: {
label: "Cancel",
className: "btn-danger btn-fixed-width-100"
},
confirm: {
label: "Save",
className: "btn-success btn-fixed-width-100"
}
},
callback: function (result) {
}
});
box.on("shown.bs.modal", function(e) {
console.log(e.currentTarget);
var selectItemLevel = document.getElementById('editItemLevel');
console.log(selectItemLevel);
$(selectItemLevel).empty();
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt);
});
$(e.currentTarget).find('select[name="editItemLevel"]').val(selectItemLevel);
$(e.currentTarget).find('input[name="editIdentifier"]').val(itemDao.item.identifier);
$(e.currentTarget).find('textarea[name="editItemValue"]').val(itemDao.item.itemValue);
});
box.modal('show');
}
});
});
}
Here is the code for the HTML file:
<form id="editItem" action="/api/items/save" method="post">
<input type="hidden" name="artifactId" id="artifactId" value="" />
<input type="hidden" name="editId" id="editId" value="" />
<input type="hidden" name="editSysId" id="editSysId" value="" />
<input type="hidden" name="editSortIndex" id="editSortIndex" value="" />
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemLevel">Item level:</label>
<select class="form-control" id="editItemLevel" name="editItemLevel"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="editItemClass">Item class:</label>
<select class="form-control" id="editItemClass" name="editItemClass" onchange="itemEditClassChange();"></select>
</div>
</div>
</div>
<div class="row" id="editRequirementRow">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemType">Requirement type:</label>
<select class="form-control" id="editItemType" name="editItemType"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="createIdentTemplate">Identifier prefix:</label>
<select class="form-control" id="editIdentTemplate" name="editIdentTemplate" onchange="itemEditIdentTemplateChange();"></select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="createMediaType">Media type:</label>
<select class="form-control" id="editMediaType" name="editMediaType"></select>
</div>
</div>
<div class="col-sm-6" id="editIdentField">
<div class="form-group">
<label for="editIdentifier">Identifier:</label>
<input type="text" class="form-control" id="editIdentifier" name="editIdentifier" />
</div>
</div>
</div>
<div class="form-group">
<label for="editItemValue">Item details:</label>
<textarea class="form-control" rows="5" cols="50" id="editItemValue" name="editItemValue"></textarea>
</div>
And here is the output intended for one of the SELECT controls as printed by console.log();
<select class="form-control" id="editItemLevel" name="editItemLevel">
<option value="1">Level 1</option>
<option value="2">Level 2</option>
<option value="3">Level 3</option>
<option value="4">Level 4</option>
<option value="5">Level 5</option>
<option value="6">Level 6</option>
<option value="7">Level 7</option>
<option value="8">Level 8</option>
<option value="9">Level 9</option>
<option value="10">Level 10</option>
It seems your each loop is not properly appending the <option></option>.If you have chrome developer tools and you know how to use it, put a breakpoint in this function and make sure the select options are being created and added to the DOM:
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt); //breakpoint here
});
Also, since you are already using jQuery, you could add them to the DOM like this:
$.each(itemDao.itemLevels, function (key, index) {
$(selectItemLevel).append('<option value="'+index+'">Level '+index+'</option>');
});
Thanks to #nilerafetr24, but the problem was not about appending properly. Rather it was about how to get hold of the SELECT control before being shown.
Certainly, the following doesn't work document.getElementById('editItemLevel'), but the following works $(e.currentTarget).find('select[name="editItemLevel"])'.
So, my final solution is to rewrite the loop thus; after combining with the solution suggested by #nilerafetr24 which seems more efficient:
$.each(itemDao.itemLevels, function (key, index) {
$(e.currentTarget).find('select[name="editItemLevel"]).append('<option=value="'+index'">Level '+index+'</option');
});
I have a form that needs to be submitted and the data sent to mysql with Ajax and jQuery, however when clicking submit, the page refreshes and the jQuery code is not running.
Here is my HTML code:
<form class="form-horizontal" role="form" action="" method="post">
<input type="text" id="firstname" class="form-control" placeholder="Firstname" required=""></br>
<input type="text" id="lastname" class="form-control" placeholder="Lastname" required=""></br>
<input type="text" id="signup_email" class="form-control" placeholder="Email address" required=""></br>
<select id="gender" class="form-control">
<option>Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select></br>
<input type="password" id="signup_password" class="form-control" placeholder="Password" required="">
<input type="submit" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
</form>
And here is my jQuery:
<script type="text/javascript">
$(function()){
$("#signup_button").click(function() {
var firstname = $("input#firstname").val();
var lastname = $("input#lastname").val();
var email = $("input#signup_email").val();
var gender = $("select#gender").val();
var password = $("input#signup_password").val();
var datastring = 'new=yes'+'&firstname='+firstname+'&lastname='+lastname'&email='+email+'&gender='+gender+'&password='+password;
$.ajax({
type:"POST";
url:"api/signup.php";
data: datastring;
cache: true;
success: function(html) {
$.("#alert_succes_congrats").css('display', '');
}
})
return false;
})
}
</script>
Thank you.
You have two options to solve your problem:
1st option:
Change
<input type="submit" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
To
<input type="button" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
So the button will not trigger a form submit.
2nd option:
Put an event.preventDefault at your click handler.
$("#signup_button").click(function(event) {
/* Your stuff */
event.preventDefault();
}
So it will not trigger browser default action to form submit button.
You code has lot of syntax error:
$(function()){
Should be
$(function(){
Plus the ajax members should be separated by comma and not semi-colon, there was issue in string concatenation as well. Next time this happens, please check the browser console for any javascript issues.
This should work
<script type="text/javascript">
$(function(){
$("#signup_button").click(function() {
var firstname = $("input#firstname").val();
var lastname = $("input#lastname").val();
var email = $("input#signup_email").val();
var gender = $("select#gender").val();
var password = $("input#signup_password").val();
var datastring = 'new=yes'+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&gender='+gender+'&password='+password;
$.ajax({
type:"POST",
url:"api/signup.php",
data: datastring,
cache: true,
success: function(html) {
$("#alert_succes_congrats").css('display', '');
}
});
return false;
});
});
http://jsfiddle.net/Nvt2h/
I am using this script which sends details from input fields to my email. As you can see, there is input.error which highlights the field in red if there is an incorrect entry. However, this currently works only for Field 1 and Field 4.
How can I make this work on field 2 and 3 as well ?
<form id="contact" name="contact" action="#" method="post">
<div class="form-group">
<label for="msg">Field1:
</label>
<input name="msg" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="id">Field2:</label>
<input name="id" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="pb">Field3:
</label>
<input name="pb" type="msg" class="form-control" id="pb">
</div>
<div class="form-group">
<label for="email">Field4:</label>
<input name="email" type="email" class="form-control" id="email">
</div>
<button id="send">Submit</button>
Add a minlength attribute to those input fields
<input name="msg" type="msg" class="form-control msg" id="msg" minlength="2">
then
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function () {
//$(".modalbox").fancybox();
$("#contact").submit(function () {
return false;
});
$("#send").on("click", function () {
$('#contact input.error').removeClass('error');
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#email").addClass("error");
}
var minlen = $('#contact input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
type: 'POST',
url: 'send.php',
data: $("#contact").serialize(),
dataType: 'jsonp',
success: function (data) {
if (data.result == true) {
$("#contact").fadeOut("fast", function () {
$(this).before("<p class='success'><strong>Thank you, your message has been sent. We will be in touch shortly.</strong></p>");
});
} else { /* if you want to handle mail send failed, put it here */
}
},
error: function (jqXHR, textStatus, errorThrown) {
// this is triggered if there's a problem getting the jsonp back from the server
}
});
}
});
});
Demo: Fiddle