Load Partial view after page is loaded - javascript

I have a view that contains a dropdown on load, when the dropdown value is changed it loads a partial view blow the dropdown containing an input form. This works correctly.
Now when i open the page, but the dropdown value has already been selected i need to load that same partial view.
But when i do this the entire layout get's loaded again and not my partial view.
Both these post back to the same action. Does anyone have an idea.
Please look at the images below for the outputs.
$('#DbDropdown').on('change', function (evt) {
LoadBody();
});
$(window).bind("load", function () {
var e = document.getElementById("DbDropdown");
var text = e.options[e.selectedIndex].value;
if (text != "Please select")
{
LoadBody();
}
});
function LoadBody()
{
var url = "GetHeader";
var $Detail = $("#HeaderSection")
$.ajax({
data: $("#PRForm").serialize(),
type: 'GET',
cache: false,
dataType: 'html',
url: url,
success: function (result) {
$Detail.html(result);
},
error: function (ex) {
alert(ex);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#model PRHeaderVM
<section>
<h2>Purchase Requesition #Model.PrNumber
</h2>
<form asp-action="SubmitPR" role="form" id="PRForm" style="width: 100%;top:0;right:0;left: 10px; bottom:10px" enctype="multipart/form-data">
#Html.HiddenFor(x => x.PrNumber)
#Html.HiddenFor(x => x.Status)
<div style="margin-top : 10px; position:fixed;top:50px;right:50px;width : 150px">
#if (Model.Status == 1)
{
Html.RenderPartial("_CreateButtonTemplate");
}
#if (Model.Status == 2)
{
Html.RenderPartial("_ApproveButtonTemplate");
}
</div>
<div class="form-horizontal">
<div class="row">
<div class="col-lg-3">
<div class="form-group">
<div style="padding-bottom: 40px;">
<label class="col-lg-4 control-label">Company</label>
<div class="col-lg-8">
<select id="DbDropdown" asp-for="CompanyID" asp-items="#Model.Companies" class="form-control">
<option>Please select</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div id="HeaderSection">
</div>
</div>
</form>
</section>
Selecting the value myself
Selecting the value myself
Value loaded from model
Value loaded from model

The answer below should do it (was deleted, see comments). One more input:
As of jQuery 3.0, .bind() has been deprecated.
You are using on your first line .on and on the 4th line .bind. .on has replaced .live and .bind so you should use .on on every element for future development.
$('#DbDropdown') *.on* ('change', function (evt) {
LoadBody();
});
$(window) *.bind* ("load", function () {

Resolved by Specifying the url for the on form load ajax call.
function LoadPRBody(url) {
var $Detail = $("#HeaderSection");
alert($("#PRForm").serialize().toString());
$.ajax({
data: $("#PRForm").serialize(),
type: 'GET',
cache: false,
dataType: 'html',
url: url,
success: function (result) {
$Detail.html(result);
},
error: function (ex) {
alert(ex);
}
});
}
$('#DbDropdown').on('change', function (evt) {
LoadPRBody("GetHeader");
});
$(window).on("load", function () {
var val = $('#DbDropdown').val();
alert(val);
if (val != 0) {
LoadPRBody("#Url.Action("GetHeader", "Requests")");
}
});
The issue seemed to be that the url was not being loaded correctly that the point when the ajax reqest was made, thus not knowing in which controller to look for the action.

Related

Submitting 2 forms separately via AJAX - Python Flask

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.

Jquery Flask capturing checkbox value

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)

Populating MVC 5 View ComboBox using Javascript based on another ComboBox selection

I'm working on an ASP.NET Core MVC web project and I want to populate values of ComboBox B (Churches) based on selection of ComboBox A (Stations) using JavaScript (Json). I have tried to research with no success.
Here are my codes:
MVC View Code:
<div class="form-group">
<label asp-for="RSTATIONID" class="col-sm-4 control-label">Station:</label>
<div id="station" class="col-sm-8">
<select asp-for="RSTATIONID" class="form-control" asp-items="ViewBag.RSTATIONID"
onchange="LoadChurches(this)"></select>
<span asp-validation-for="RSTATIONID" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="RCHURCHID" class="col-sm-4 control-label">Church:</label>
<div id="church" class="col-sm-8">
<select asp-for="RCHURCHID" class="form-control" asp-items="ViewBag.RCHURCHID"></select>
<span asp-validation-for="RCHURCHID" class="text-danger" />
</div>
</div>
JavaScript Code:
function LoadChurches(e) {
var stationID = e.value;
//alert(stationID);
$.ajax
({
url: '/CaptureReceipts/LoadChurches',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stationID: +stationID
}),
success: function (result) {
var res = result.value;
alert(JSON.stringify(res));
/*$("#church").html("");
$.each($.parseJSON(result), function (i, church) {
SetSel(this);
}); */
},
error: function () {
alert("Churches can not load");
}
});
}
Controller Code:
public JsonResult LoadChurches(string statID)
{
int stationID = Convert.ToInt32(statID);
var churches = new SelectList(_context.v_Church.Where(m => m.StationID == stationID), "ID", "churchName");
return Json(ViewData);
}
The Controller name is CaptureReceiptsController. Please help me know what may be wrong.
In controller return simple json array:
var churches = _context.v_Church
.Where(m => m.StationID == stationID)
.Select(x => new {id = x.ID, name = x.churchName })
.ToArray();
return JSON(churches);
In success callback:
success: function (data) {
var churchSelect = $("#church > select")
churchSelect.html(""); //clear select
for (var i =0;i<data.length;i++){
var opt = document.createElement('option');
opt.innerHTML = data[i].name;
opt.value = data[i].id;
churchSelect.append(opt);
}
}

Checkbox not getting checked via jquery

On my .html
<div class="col-md-9 col-sm-9 col-xs-12">
<div class="">
<label>
<input type="checkbox" id="SMSCheckbox" class="js-switch" /> SMS
</label>
</div>
<div class="">
<label>
<input type="checkbox" id="EmailCheckBox" class="js-switch" /> Email
</label>
</div>
</div>
On my .js
$(document).ready(initialize);
function initialize() {
console.log("loaded JS");
$.ajax({
type: "GET",
url: "./getNotificationSettings.php",
datatype: "json",
success: function(response) {
var response = JSON.parse(response);
var bySMS = response[0].receiveSMS;
var byEmail = response[0].receiveEmail;
if (bySMS) {
console.log("bySMS = true");
$('#SMSCheckbox').prop('checked', true);
} else {
console.log("bySMS = false");
$('#SMSCheckbox').prop('checked', false);
}
if (byEmail) {
console.log("byEmail = true");
$('#EmailCheckBox').prop('checked', true);
} else {
console.log("byEmail = false");
$('#EmailCheckBox').prop('checked', false);
}
},
error: function(e) {
console.log(e);
}
});
}
bySMS = true
byEmail = true
I checked my console that it does go inside the if true branch but somehow my checkbox is not being selected. It's strange that I tested it on jsfiddle and it's working.
What could be the cause of this strange issue?
Not sure if it matters that to toggle the checkbox, I had to click on the wording. Clicking on the switch doesn't toggle it.
I always use .click() on checkboxes when changing the checked property doesn't work for some reason, not sure if this is a proper way of doing it.
I created a little function to handle it for you:
$.fn.setCheckbox = function(value) {
var checked = $(this).attr("checked") != "undefined" &&
($(this).attr("checked") === "checked" ||
$(this).attr("checked") === true);
if (checked != value) {
$(this).click();
}
}
Plunker: https://plnkr.co/edit/mdAzNsZnRdl2ifIT22e0?p=preview

Not getting onchange event of dynamicly added dropdown in mvc3

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.

Categories