I am trying to capture the data from checkbox by assigning value in jquery and passing it to backend each time search is run by the user. It is not working for me, tried several ways.
Use case: As a user I would like to search and be able to check for various search options.
template:
$('a#process_input').bind('click', function () {
$.getJSON('/background_process', {
checkbox1: $('input[name="checkbox1"]').val(),
input_search: $('input[name="input_search"]').val(),
},
function (data) {
ul.empty();
$.each(data.result, function (index, element) {
...
... <some irrelevant code...>
<input type=text size=40 name=input_search>
<a href=# id=process_input>
<button class='btn btn-default'>Submit</button>
</a>
</form>
<form method="POST" action="/">
<p>Please select allergy options below:</p>
<input type="checkbox" name="checkbox1"/>Allergy 1
backend
#app.route('/background_process', methods=['GET', 'POST'])
def background_process():
try:
checkbox1 = request.args.get("something")
search_word = request.args.get('input_search', 0, type=str)
if search_word:
return jsonify(result=yummly_search(search_word, checkbox1))
else:
return jsonify(result='Try again.')
except Exception as e:
return str(e)
I am not comfortable with getJSON function but the other way to do it is ajax. Here is a runnable code, I hope it helps:
html:
<input type=text size=40 name="input_search">
<a href=# id=process_input>
<button class='btn btn-default'>Submit</button>
</a>
<p>Please select allergy options below:</p>
<input type="checkbox" name="checkbox1"/>Allergy 1
<div id="login_result"></div>
javascript:
<script>
$(document).ready(function () {
$("#process_input").bind('click', function () {
var login_result = $('#login_result');
var input_search = $('[name="input_search"]').val();
var checkbox1 = $('[name="checkbox1"]').is(":checked");
console.log(input_search);
console.log(checkbox1);
var list = new FormData()
list.append("input_search", input_search)
list.append("checkbox1", checkbox1)
var urlBackgroundProcess = "{{ url_for('background_process') }}";
var ajaxRequest = $.ajax({
type: "POST",
url: urlBackgroundProcess,
data: list,
contentType: false,
cache: false,
processData: false,
success: function (msg) {
login_result.html(msg.data);
console.log("AJAX ok 2!");
}
});
});
});
</script>
and the flask back end:
#app.route('/background_process',methods=['GET','POST'])
def background_process():
msg=''
if request.form.get("input_search"):
msg=('I got that search pattern at the back end: \'%s\' \n the checkbox value is set to: \'%s\' ') \
% (request.form.get("input_search"),request.form.get("checkbox1"))
else:
msg='I got the Ajax call but cannot read the data, try again! :('
return jsonify(data=msg)
Related
How can I send the value shown in an HTML input box as '030.34' and not '0.34'?
I need to prepend '03'for an ID.
I need the input box to be type 'number' so the up down buttons can be used, so I cannot set it to text.
Added: there are limits max min set on the input.
Any ideas?
Thanks Chris
function ipFunction() {
var c = SETPOINT.value;
SETPOINT.value = xxx + c; // prepend '03' HOW???
return true; // can be submitted
}
<form id="frmSetPoint" name="frmSetPoint" action="#" onsubmit="ipFunction()" accept-charset="utf-8">
<input type="number" onkeydown="return false" id="SETPOINT" name="SETPOINT" min="1" max="10">
<input type="submit" value="Submit Value">
</form>
I spent a day on this - I'm just learning - but a friend put me right.
Hopefully this should help others.
$("#frmSetPoint").validate({
submitHandler: function (form) {
var serializedData = $(form).serialize();
serializedData = serializedData.replace("=", "='P03") + "'";
$.ajax({
url: '/value.cgi',
data: serializedData,
type: 'GET',
success: function (data) {
},
error: function (data) {
$(currentButton).prop('disabled', false);
$(currentButton).css({
color: '#ffffff',
backgroundColor: '#00FF00'
});
}
});
return false;
}
}); //validate
I'm trying to submit 2 separate forms via AJAX, but on submitting form2 I get a 500 bad request error.
My HTML code is below, but basically my page is a flask template that works as follows:
*User makes selections
*These selections are then posted via the submit button named "button" Value "Calculate Available Overall Heights".
*This runs some SQL query to determine a list of entries that are placed into a newly generated <select id="mySelect" class="form-control" onchange="myFunction()"></select>
This is done by JS which is also listed below as MyJS.js
OAH.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="h2">XXX</p>
<form method="post" id="form1">
<fieldset>
</div>
<div class="col-sm-3">
<span style="float:left"><label>Overall Height</label></span>
///my inputs, various selects etc ///
<div id="response">
<!-- Empty element until form submitted-->
</div>
<p id="ApertureHeight"></p>
<p id="ApertureHeightBelowPelmet"></p>
<p id="ApertureHeightUnderRoofSticks"></p><br>
<p id="OverallWidth"></p>
<p id="RearAppWidth"></p>
<p id="RearPillarNS"></p>
<p id="OAH"></p>
</div>
</fieldset>
<script src="/static/js/MyJS.js"></script>
</form>
<form method="post" id="form2">
<div class="col-sm-3">
<label>
<span style="float:left"><input type="text" id="myText" value=""></span>
</label>
<br>
<input type="button" value="Click Me!" onclick="submitForms()" />
</div>
</form>
</body>
</html>
form2 has a button called "Click Me!" which calls a function that submits form 2.
submitForms = function(){
document.getElementById("form2").submit();
};
MyJS.js
$("#form1").on("submit", function(event) {
$targetElement = $('#response');
event.preventDefault();
// Perform ajax call
//
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
submitForms = function(){
document.getElementById("form2").submit();
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$("#form2").on("submit", function(event) {
event.preventDefault();
console.log("Sending data: " + $(this).serialize());
$.ajax({
url: '/OAH',
data: $('#form2').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call
})
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function myFunction() {
var FifthWheel = document.getElementById("FifthWheelHeight").value;
var NeckDepth = document.getElementById("NeckDepth").value;
var CantRailDepth = document.getElementById("CantRailDepth").value;
var RearTensioner = document.getElementById("RearTensioner").value;
var OAH = document.getElementById("mySelect").value;
if (CantRailDepth = 115) {
var PelmetDim = 100;
} else {
PelmetDim = 75;
}
var ApertureHeight = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - Number(CantRailDepth);
var ApertureHeightBelowPelment = Number(ApertureHeight) - Number(PelmetDim);
var ApertureHeightUnderRoofSticks = Number(OAH) - Number(FifthWheel) - Number(NeckDepth) - 35;
document.getElementById("ApertureHeight").innerHTML = "Aperture below Cantrail = " + ApertureHeight + "mm";
document.getElementById("ApertureHeightBelowPelmet").innerHTML = "Aperture below pelmet = " +
ApertureHeightBelowPelment + "mm";
document.getElementById("ApertureHeightUnderRoofSticks").innerHTML = "Aperture below roof sticks = " +
ApertureHeightUnderRoofSticks + "mm";
document.getElementById("OverallWidth").innerHTML = "Overall Width = 2548mm (2550mm on spec)";
document.getElementById("OAH").innerHTML = OAH;
document.getElementById("myText").value = document.getElementById("OAH").innerHTML;
}
I need this form to submit separately, via AJAX without refreshing the page, as I need the JSON array to be able to calculate further stuff that will be passed into Python Flask. My issue is I am getting a bad request when submitting form2.
Anyone got any ideas on what I have done wrong?
I think you are using the same endpoint URL to try handle 2 different requests. The 2nd form does not send the correct data and you're then getting Server errors. Try creating another endpoint on your python flask server for handling form2 and the myText field value.
Programming a ASP.net webapp to insert an entry into a database on form submit.
I've tried numerous configurations of find() and children() and they either
1) error
2) pass empty strings instead of what I type
This one errors like this:
Whats the correct way to select the individual children of myform?
Javascript (the first block here is the code I'm asking about)
var entry_array = [];
entry_array[0] = $('#myform').children('#01').css().text();
entry_array[1] = $('#myform').children('#02').css().text();
entry_array[2] = $('#myform').children('#03').css().text();
entry_array[3] = $('#myform').children('#04').css().text();
$(document).ready(function () {
$("#myform").submit(function () {
alert("Function ran");
$.ajax({
url: 'Home/SubmitEntry', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
datatype: 'json',
traditional: true,
data: { 'entry_array': entry_array },
success: function(response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
alert("Function finished running");
});
});
Controller
[HttpPost]
public ActionResult SubmitEntry(List<String> entry_array)
{
String firstname = entry_array[0];
String lastname = entry_array[1];
String town = entry_array[2];
String order = entry_array[3];
knightsEntities db = new knightsEntities();
int nextiD = 0;
nextiD = db.Apprentenceship_Sheet.ToList().Last().id + 1;
var newApprentenceship_Sheet = new Apprentenceship_Sheet();
newApprentenceship_Sheet.first_name = firstname;
newApprentenceship_Sheet.last_name = lastname;
newApprentenceship_Sheet.hailed_town = town;
newApprentenceship_Sheet.order = order;
newApprentenceship_Sheet.id = nextiD;
db.Apprentenceship_Sheet.Add(newApprentenceship_Sheet);
db.SaveChanges();
return View();
}
View
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="~/scripts/custom.js"></script>
#{
ViewBag.Title = "Home Page";
}
<div>
<form id= "myform" method="post">
First_name:<br>
<input type="text" id="01" name="firstname"><br>
Last_name:<br>
<input type="text" id="02" name="lastname"><br>
Town:<br>
<input type="text" id="03" name="town"><br>
Order:<br>
<input type="text" id="04" name="order"><br>
<br>
<input type='submit' id="05" name="Submit">
</form>
</div>
You can get the values of the text boxes directly by using $('#01').val(), or if you want refer it with reference to your form. You can use $('#myform').find('#01').val(). It will give the value of the text-box. Here is the jsfiddle for u.
$('#myform').find('#01').val()
$('#01').val()
http://jsfiddle.net/71weztcn/
I have a method in my controller
def returnJames = {
JSONObject jsonObject = new JSONObject()
jsonObject.put("name","James")
return jsonObject
}
and then I have a view:
<html>
<!--import gsp that has all the jquery imports-->
<script>
function changeName()
{
$.ajax({
url:"<g:createLink url="[action:'returnJames',controller:'mycontroller']" />",
dataType: "json",
asnyc: false,
success: function(data) {
$('mytextbox').val(it.name)
}
});
}
</script>
<g:form controller="mycontroller" method="post" >
<g:textField name="mytextbox" value="" />
<button name = "mybutton" id = "mybutton" onclick="changeName()">change name</button>
</g:form>
</html>
However it just tries to change the page to the index view of the mycontroller controller which doesn't exist. How can I get it to just fill in the textbox with "James"?
User render instead of return
render jsonObject
and change in jQuery
success: function(data) {
$('#mytextbox').val(data.name)
}
change button to
<input type="button" id = "mybutton" onclick="changeName()" value="change name"/>
I have three dropdownlists.
$(document).ready(function () {
$("#DropDownList1").change(function () {
$("#Id1").val($(this).val());
$("#Name1").val($("#DropDownList1 option:selected").text());
$('#Div1').load('/Account/Dropdown2/?Id1=' + $("#Id1").val());
});
$("#DropDownList2").change(function () {
$("#routeId").val($(this).val());
$("#routeName").val($("#RouteDropDownList option:selected").text());
$('#Div2').load('/Account/Dropdown3/?Id2=' + $("#routeId").val());
});
$("#DropDownList3").change(function () {
$("#Id3").val($(this).val());
$("#Name3").val($("#DropDownList3 option:selected").text());
});
});
In this DropDownList2 and DropDownList3 are added dynamicly.The problem is the dynamicly added dropdowns are not got registered in the page .So I am not getting its selected value from the onchange event.I added these controls as partial view.
Controller.
public ActionResult DropDownList2 (string Id1)
{
List<Emp> empList = new List<Emp>();
Emp em= new Emp ()
{
Id = "1",
Name = "Doac"
};
empList .Add(em);
ViewBag.DropDownList2= new SelectList(empList , "Id", "Name");
return PartialView();
}
Generated Html
<script type="text/javascript">
$('#CreateSubscriber').removeClass('menuHolderli').addClass('selectedMenu');
$(document).ready(function () {
$("#DropDownList").change(function () {
$("#Organization_Id").val($(this).val());
$("#Organization_Name").val($("#DropDownList option:selected").text());
$('#routeDiv').load('/Account/RouteDropdown/?organizationId=' + $("#Organization_Id").val());
});
$(document).on('change', "#RouteDropDownList", function () {
alert("hi");
$("#routeId").val($(this).val());
$("#routeName").val($("#RouteDropDownList option:selected").text());
$('#locationDiv').load('/Account/LocationDropdown/?routeId=' + $("#routeId").val());
});
$("#LocationDropDownList").change(function () {
$("#locationId").val($(this).val());
$("#locationName").val($("#LocationDropDownList option:selected").text());
});
});
</script>
<p class="message-info">
Passwords are required to be a minimum of 6 characters in length.
</p>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<form action="/Account/Register" method="post"> <fieldset>
<legend>Registration Form</legend>
<ol>
<li>
<label for="Organization_Name">Name</label>
<input id="Organization_Id" name="Organization.Id" type="hidden" value="" />
<input id="Organization_Name" name="Organization.Name" type="hidden" value="" />
<select id="DropDownList" name="DropDownList"><option value="">---Select---</option>
<option value="516c0a18c891870f107aa74a">Choice School</option>
<option value="516d277bc8918701a44c131e">New Org</option>
<option value="516d1f492e6bba07dc245cc7">Olive</option>
</select>
<span class="field-validation-valid" data-valmsg-for="Organization.Name" data-valmsg-replace="true"></span>
</li>
</ol>
<div id="routeDiv"></div>
<div id="locationDiv"></div>
Use jQuery .on()
$(document).on('change', "#DropDownList2", function(){your code})
Repeat for your dropdown 3
Since, DropDownList2 and DropDownList3 are added dynamicly, you need to do this:
$(document).on('change', '#DropDownList1', (function () {
$("#Id1").val($(this).val());
$("#Name1").val($("#DropDownList1 option:selected").text());
$('#Div1').load('/Account/Dropdown2/?Id1=' + $("#Id1").val());
});
Similarly call other dyanmically added dropdowns also.
If you are adding the select options dynamically, why not use AJAX within AJAX?
$(function() {
$('#DropDownList').each(function () {
var dropdown = $(this);
dropdown.change(function() {
$.ajax({
url: 'Account/GetDropDownOptions',
type: 'GET',
data: {dropdownID: dropdown.attr('id'), value: dropdown.val()},
dataType: 'html',
cache: false,
success: function (data) {
var dropdown2 = $('#DropDownList2');
dropdown2.html(data);
dropdown2.change(function() {
$.ajax({
url: 'Account/GetDropDownOptions',
type: 'GET',
data: {dropdownID: dropdown2.attr('id'), value: dropdown2.val()},
dataType: 'html',
cache: false,
success: function (data) {
var dropdown3 = $('#DropDownList3');
dropdown3.html(data);
dropdown3.change(function() {
//....same thing as above pretty much
});
}
});
});
}
});
});
});
});
Then your controller action, GetDropDownOptions, would examine the DDL ID and selected value, understand what options it needed, then return the options as HTML. Or as a more elegant solution, you could have it return an object as json ( return Json(object) ) and then programatically create the elements in your javascript. You'd have to switch the dataType in the $.ajax to 'json'.
This way you have the dropdown change event after it has loaded the options. This change event loads DropDownList2's options and change event, which will load DDL3's options.
Haven't tested the code, but this idea will work. This sample assumes you already have the first DDL options loaded, but it seems you'll have to have add another layer of ajax to load those in as well. It also assumes the and DDL3 are already on the DOM at page load. You could add them to the DOM in your html to get this example to work, or change the IDs in the javascript to some container.