MVC 4.x Validate dropdown and redirect to next page - ajax

Beginner question:
I have an MVC app where there are three dropdowns on a page. Currently I'm using AJAX to evaluate a drop down on form submission and modify a CSS class to display feedback if the answer to the question is wrong.
HTML:
<form method="post" id="formQuestion">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>This is a question:</p>
</div>
<div class="col-md-4">
<select id="Question1">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col-md-4 answerResult1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button class="btn btn-success" type="submit" id="btnsubmit">Submit Answer</button>
</div>
</div>
</form>
AJAX:
#section scripts {
<script>
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) { $(".answerResult1").html(data); }
});
})
});
</script>
}
Controller:
public string DSQ1(string selectedAnswer1)
{
var message = (selectedAnswer1 == "3") ? "Correct" : "Feed back";
return message;
}
I have three of these drop downs, that all get evaluated by AJAX in the same way. My question is, how would I go about evaluating all three and then returning a particular View if all three are correct.
I would like to avoid using hard-typed http:// addresses.

You could declare a global script variable prior to your document ready function, this will determine if the fields are valid. See var dropdown1Valid = false, ....
Then on your ajax success function, you could modify the values there. Say in the ajax below, your answering with first dropdown, if your controller returned Correct, set dropdown1Valid to true.
Lastly, at the end of your submit function, you could redirect check if all the variables are true, then redirect using window.location.href="URL HERE or use html helper url.action window.location.href="#Url.Action("actionName");
#section scripts {
<script>
var dropdown1Valid = false;
var dropdown2Valid = false;
var dropdown3Valid = false;
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) {
$(".answerResult1").html(data);
if(data == "Correct"){
// if correct, set dropdown1 valid to true
dropdown1Valid = true;
}
// option 1, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName","controllerName", new { })";
}
}
});
// option 2, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName", "controllerName", new { })";
}
})
});
</script>
}

Related

How to get value from radio button dynamically

i am creating a form for searching a client, using either id or email both are set to be unique. Application made on Codeignitor.
I have created a form with two radio buttons, one for search with ID and another for search with mail+dob.
Depending on the radio button selected, corresponding input fields shown.
In controller, it choose the model function based on the radio button value.
This is I coded, i need to pass the value of radio button to Controller.php file
Form(only included the radio button)
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="mail">Using DOB</label>
</div>
I expected to get the radio button value correctlyenter image description here
JS:
$('input[name="optradio"]').click(function(){
var optradio = $(this).val();
//or
var optradio = $("input[name='optradio']:checked").val();
if(optradio == 'id'){
//do your hide/show stuff
}else{
//do your hide/show stuff
}
});
//on search button press call this function
function passToController(){
var optradio = $("input[name='optradio']:checked").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('controller/cmethod'); ?>",
data: ({optradio : optradio}),
success: function (data) {
}
});
}
Try this
<script type="text/javascript">
$( document ).ready(function() {
$("#usingdob, #usingmail").hide();
$('input[name="radio"]').click(function() {
if($(this).val() == "id") {
$("#usingId").show();
$("#usingdob, #usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob, #usingmail").show();
}
});
});
</script>
One thing I noticed is that you have 'mail' as a value in the DOB option. Another is that there seems to be 3 options and yet you only have 2 radios?
I adjusted the mail value to dob and created dummy divs to test the code. It seems to work.
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
console.log($(this).val());
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="dob">Using DOB</label>
</div>
<div id="usingId">
Using Id div
</div>
<div id="usingdob">
Using dob div
</div>
<div id="usingmail">
Using mail div
</div>
As far as passing the value to the controller goes, ideally the inputs should be in a form. When you submit the form, the selected value can be passed to the php.
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['optradio']))
{
Radio selection is :".$_POST['optradio']; // Radio selection
}
?>
If you want to get currently checked radio button value Try below line which will return current radio button value
var radioValue = $("input[name='gender']:checked").val();
if(radioValue)
{
alert("Your are a - " + radioValue);
}

Ajax submit and replace submit button with checkmark after success

First, I'm not having luck with ajax submitting at all in cakephp 1.3 environment. Once I successfully submit, I'm hoping user stays on page and submit button hidden or replaced with a checkmark. I've tried a few things... controller without $action and then .click function instead of on submit. I'm also not versed in debugging js to see where it might be wrong so any suggestions are welcome.
Maybe "update_a" is the $action within my dashboard controller
"function applications($action) {" instead?
dashboard controller
function update_a($action) {
...
switch ($action) {
case 'save':
if (!empty($this->data)) {
// update fields in database table matching model
$this->data['Model']['submitted'] = $_POST['submitted'];
$this->data['Model']['locked'] = $_POST['locked'];
if ($this->Model->save($this->data)) {
// save form fields to other models
$this->OtherModel->saveField('form_status_id',$_POST['form_status_id']);
$this->OtherModel->saveField('form_status',$_POST['form_status']);
}
}
}
break;
default:
//$this->redirect("admin/index");
$this->render("dashboard/applications");
break;
} //case
} // end function
html
<body>
<form id='update_a' action='save'>
<div class='form-group'>
<input type='hidden' class='hidden' name='locked' id='locked' value='1'>
<input type='hidden' class='hidden' name='form_status' id='form_status' value='Locked'>
<input type='hidden' class='hidden' name='form_status_id' id='form_status_id' value='3'>
<input type='hidden' class='hidden' name='submitted' id='submitted' value='<?php echo date("Y-m-d G:i:s") ?>'>
</div>
<div class='text-center'>
<input name='submit' type='button' class='btn btn-default' value='Submit Form A'>
</div>
</form>
</body>
<script>
$(document).ready(function () {
$('#update_a').on('submit', function (e) {
//$('#update_a').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/dashboard/update_a',
data: $('#update_a').serialize(),
success: function () {
alert('Form A has been submitted and locked for editing');
$('#update_a').hide();
},
error : function() {
alert("Error");
}
});
return false;
});
});
</script>

Using ng-repeat after $http call

I'm learning Angular (1.6.6), so I'm hoping/assuming I'm missing something basic.
I'm populating a drop-down menu on ng-init, which is working as expected. I'm returning JSON from the DB, and console.log() shows me that the JSON is pulling through as expected.
I'm stuck with ng-repeat, trying to display the data in another div.
My Controller
app.controller('RandomTownCtrl', [
'$scope',
'$http',
function($scope, $http){
window.MY_SCOPE = $scope;
$scope.getAllRegions = function() {
$http({
method: 'GET',
url: '/all-regions'
}).then(function successCallback(response) {
$scope.regions = response.data;
}, function errorCallback(response) {
console.log('error');
});
};
$scope.getRandomTown = function() {
var guidEntity = $scope.guidEntity;
if (typeof guidEntity === 'undefined') { return };
$http({
method: 'GET',
url: '/region-name?region-guid=' + guidEntity
}).then(function successCallback(response) {
$scope.randomTown = response.data;
console.log($scope.randomTown);
}, function errorCallback(response) {
});
};
}
]);
The Markup
<div class="column col-sm-5 content-column">
<form ng-controller= "RandomTownCtrl" ng-init="getAllRegions()" ng-submit="getRandomTown()">
<h3>Generate Random Town</h3>
<div class="form-group">
<select name="nameEntity"
ng-model="guidEntity"
ng-options="item.guidEntity as item.nameEntity for item in regions">
<option value="" ng-if="!guidEntity">Choose Region</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Generate!</button>
</form>
</div>
<div class="column col-sm-5 content-column" id="output-column">
<div class="header">
<h4>Region Name:</h4>
</div>
<div ng-controller='RandomTownCtrl'>
<p ng-repeat="item in randomTown">
{{ item.name_region }}
</p>
</div>
</div>
You are mixing $scope and self together, you need also ng-repeat needs an array not an object.
$scope.randomTown = response.data;
Beginner Angular mistake: I didn't understand that the ng-controller directive created an isolate scope, and the output I was expecting wasn't happening because the data simply wasn't there in that scope.

Form post from partial view to API

I am trying to create an SPA application using Sammy. When I call #/entitycreate link, I return a partial view from Home controller which contains an html form to submit. Partial view comes as I expect but rest of it doesn't work. Below are my problems and questions, I'd appreciate for any help.
KO binding doesn't work in partial view, even though I did exactly how it's done in the default SPA project template (see home.viewmodel.js).
This one is the most critical: when I submit this form to my API with ajax/post, my model always comes back with a null value, therefore I can't create an entity via my API. I have tried with [FromBody] and without, model always comes null.
In some sense a general question, should I include Html.AntiForgeryToken() in my form and [ValidateAntiForgeryToken] attribute in my API action?
Partial View:
#model namespace.SectorViewModel
<!-- ko with: sectorcreate -->
<div class="six wide column">
<div class="ui segments">
<div class="ui segment">
<h4 class="ui center aligned header">Create New Sector</h4>
</div>
<div class="ui secondary segment">
<form id="entity-create-form" class="ui form" action="#/sectorcreatepost" method="post" data-bind="submit: createEntity">
<!-- I am not sure if I should include AntiForgeryToken for WebAPI call -->
<!-- Html.AntiForgeryToken() -->
<fieldset>
<div class="field required">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { data_bind = "value: name" })
</div>
<div class="ui two buttons">
<button class="ui positive button" type="submit">Create</button>
<button class="ui button" type="button" id="operation-cancel">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!-- /ko -->
JS View Model:
function SectorCreateViewModel(app, dataModel) {
var self = this;
self.name = ko.observable("ko binding doesn't work");
self.createEntity = function () {
console.log("ko binding doesn't work");
}
Sammy(function () {
this.get("#sectorcreateget", function () {
$.ajax({
url: "/home/getview",
type: "get",
data: { viewName: "sectorcreate" },
success: function (view) {
$("#main").html(view);
}
});
return false;
});
this.post("#/sectorcreatepost",
function () {
$.ajax({
url: "/api/sectors",
type: "post",
data: $("#entity-create-form").serialize(),
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
}
});
return false;
});
this.get("#/yeni-sektor", function () {
this.app.runRoute("get", "#sectorcreateget");
});
});
return self;
}
app.addViewModel({
name: "SectorCreate",
bindingMemberName: "sectorcreate",
factory: SectorCreateViewModel
});
API Action:
public HttpResponseMessage Post([FromBody]SectorViewModel model)
{
// model is always null, with or without [FromBody]
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest);
// repository operations...
return response;
}
I have removed contentType: "application/json; charset=utf-8", from ajax request based on the article here. #2 is now resolved, #1 and #3 still remains to be answered.

issue with ajax event

i am using an ajax event which is triggered when i hit the submit button to add data to the database but since when i orignally created this page they were all in seprate files for testing purposes so now when i have put all the code together i have notice that 4 submit buttons i was using to refresh the page and then change the data being seen by filtering it are triggering the ajax query i have placed the code bellow.. i am quite stumped in what is the only way to go about this...
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var process= $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php',
data: {
'uname': checkVal,
'id': userid
},
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
});
$('form').bind('submit', function(){ // it is triggering this peice of code when the submit buttons are clicked ???
$.ajax({
type: 'POST',
url: "requestadd.php",
data: $("form").serialize(),
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
return false;
});
$("#claim").change(function(){
$("#area").find(".field").remove();
//or
$('#area').remove('.field');
if( $(this).val()=="Insurance")
{
$("#area").append("<input class='field' name='cost' type='text' placeholder='Cost' />");
}
});
});
</script>
</head>
<body>
<div id="add">
<form name="form1aa" method="post" id="form1a" >
<div id="area">
<input type=text name="cases" placeholder="Cases ID">
<select id="claim" name="claim">
<option value="">Select a Claim</option>
<option value="Insurance">Insurance</option>
<option value="Warranty">Warranty</option>
</select>
</div>
<select name="type" onChange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="">Select One</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<br />
<input type=text name="comment" placeholder="Comments Box">
<input type="submit" value="Submit" name="Submit">
</form>
</div>
<?
$sql="SELECT * FROM $tbl_name ORDER BY cases ASC";
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%' ORDER BY cases ASC";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%' ORDER BY cases ASC";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%' ORDER BY cases ASC";
}
$result=mysql_query($sql);
?>
<!-- Filter p1 (Start of) !-->
<form action="ajax-with-php.php" target="_self">
<input type="submit" name="all" value="All" /> // the issue is mainly occuring here when i click any of thesse meant to refesh the page and change the query with the if statements but is trigger the other code i commented
<input type="submit" name="tpc" value="TPC" />
<input type="submit" name="drc" value="DRC" />
<input type="submit" name="bsc" value="BSC" />
</form>
$('form').bind('submit', function(){ ...
will bind to all forms. Change it to
$('form#form1a').bind('submit', function(){ ...
and it will only bind to the first form, not the second.
$('form').bind('submit', function(event){
event.preventDefault();
$.ajax({...
Try making the changes above 1) adding the event argument to your callback 2) executing the .preventDefault() method. When using AJAX with the submit event this is neccessary to stop the page from reloading and interrupting your async request.
There may be more issues than that, but hopefully that will get you on the right track.

Resources