On my view page I have it where a user can click my 'Add Part' button to add the part they selected from the dropdown. This looks like this
<div id="Part" class="row">
<div class="col-md-2">
#Html.DropDownList("PartID", null, "-- Select --", htmlAttributes: new { #class = "form-control chosen-select Part-select" })
</div>
<div class="col-md-2">
<input type="button" value="Add Part" class="btn" onclick="add()"/>
</div>
</div>
As you can see it includes my button that should call my add() JavaScript function that looks like this
<script type="text/javascript">
function add() {
var token = $("input[name='__RequestVerificationToken']", "#__AjaxAntiForgeryForm").val();
var parts = [];
// Get all part ids and store them in arrays
var partssel = document.getElementsByClassName("Part-select");
for (i = 0; i < partssel.length; i++) {
parts[i] = partssel[i].options[partssel[i].selectedIndex].value;
}
alert("I am an alert box!");
$.ajax({
type: "POST",
url: "#IGT.baseUrl/JODetailsAjax/AddUnits",
traditional: true,
data: {
__RequestVerificationToken: token,
jo_id: #Model.Id,
addPart_id: parts
},
success: function (data) {
if (data.success === "False") {
var errorMessage = data.Message;
alert("Error: " + errorMessage);
return;
}
},
error: function (jqXHR, status, error) {
alert("Error:" + error);
}
});
}
</script>
I verified it's running the method as it hits the Alert, but when it goes through the AJAX section of it, it always returns the 'error' alert in the AJAX method instead of going to my POST Method in my controller. (I verified it's not hitting my POST method by putting a breakpoint at the beginning of it)
Here is what is showing in the network tab of my developer console
Why is this not working?
Related
have a button click in a form and have required validation when clicking on that button. I put in
if (!formHandle.valid()) { return; }
in the global site.js file where I want that event to fire first before the event for the actual button. Currently the jquery for the actual button fires first before the global jquery. How can I make sure that the global jquery fires first or is this even possible?
html
<p id="vote-status" class="card-text forum-blue">
#{if (#Model.VoteId != 0)
{
<text>
<br /Text.
<br />Text
</text>
}
else
{
<text><br />Text.</text>
}
}
</p>
#{
if (Model.AvailableVotingOptions != null)
{
#Html.DropDownListFor(m => m.VotingOptionId,
Model.AvailableVotingOptions,
"- Please select -",
new { #class = "form-control", #id = "voting-options" })
}
}
<div class="card-footer">
<div class="row">
<div class="col-sm-12 col-md-3 col-lg-3">
<button type="button"
class="btn btn-success btn-sm col-sm-12"
id="button"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
</div>
</div>
Site.js (event I want to hit first)
$(document).on("click",
'[data-action="submit"]',
function (e) {
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
}
});
Document.js
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/bootsy1974/pen/ExggoQg
why do different functions? you can make a check before sending in the second function.
if its possible and this same one button
if its not possible to try after validation use
$("#button").trigger("click");
$(document).on("click",
'[data-action="submit"]',
function (e) {
e.preventDefault();
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
$("#button").trigger("click");
}
});
but formHandle.valid is not a function
need changed '#button' from button and created another element to binding this function. in another to try sending without validation. need do dependeces sending from validating. but you have to parallel working.
<div class="col-sm-12 col-md-3 col-lg-3">
<div id="button"></div>
<button type="button"
class="btn btn-success btn-sm col-sm-12"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
and this have not '}'
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/romanown/pen/QWKKERZ
deleted not worked validating
https://codepen.io/romanown/pen/zYKKKqv
I don't know what I am doing wrong here. but jquery validation is not working in partialview.
let me explain what I did
I am loading parial view from parent (It is not ajax load)
Parent
<div id="EmailInformationBlock" class="profileSection">
<div class="sectionTitle">
<span>Email</span>
</div>
<div id="DivEmailContainer" style="display:block">
#Html.Partial("_DisplayEmail", Model)
</div>
<hr />
</div>
Partial view
#using (Html.BeginForm(null, null, FormMethod.Get, new { name = "frmEmail", id = "frmEmail" }))
{
<td>#Html.Label("Email Location", new { #class = "control-label" })</td>
<td>
#Html.DropDownListFor(model => model.CommunicationLocation,
Enumerable.Empty<SelectListItem>(),"Select ",
new { #class = "input-validation-error form-control",
#name="CommunicationLocationEmail" }
)
}
</td>
}
<script type="text/javascript">
$(function () {
$.validator.addMethod("selectNone",
function (value, element) {
return this.optional(element) || element.selectedIndex != 0;
},
"Please select an option."
);
$("#frmEmail").validate({
rules: {
CommunicationLocation: {
selectNone: true
}
},
messages: {
CommunicationLocation: {
selectNone: "This field is required"
}
},
submitHandler: function (form) {
('#frmEmail').submit(function () {
$.ajax({
url: 'customer/PostEditEmail',
type: 'Post',
data: $(this).serialize(),
success: function (result) {
// $('#DivEmailContainer').html(result);
}
});
});
}
});
$.ajax({
url: "customer/GetCommunicationLocationList",
type: 'GET',
dataType:"json",
success: function(d) {
// states is your JSON array
var data = d.Data;
// alert(JSON.stringify(d.Data));
$.each(data, function (i) {
if (data[i].Description != "Bulk Dues"){
var optionhtml = '<option value="' +
data[i].Code + '">' + data[i].Description + '</option>';
$("#CommunicationLocation").append(optionhtml);
}
});
},
error: function (xhr) { alert("Something seems Wrong"); }
});
});
</script>
After I submit form is redirecting to new url. It shouldn't go to any url.
what I am doing wrong here.
I might be wrong, but it looks like jquery is not aware that the partial view has any validation because it is loaded from a parent view.
Try reparsing the DOM by adding the following to your partial view
$(function(){
jQuery.validator.unobtrusive.parse();
jQuery.validator.unobtrusive.parse("#frmEmail");
});
and this to you parent view
$(function(){
$("#submitButtonId").click(function(){
if (!$("#frmEmail").valid()){
return false;
}
});
});
You effectively have ajax within a submit within a submit...
submitHandler: function (form) {
('#frmEmail').submit(function () {
$.ajax({
....
});
});
}
You forgot the $ in front of the ('#frmEmail') selector, which breaks everything inside the submitHandler, but that's not really the core issue here.
After I submit form is redirecting to new url.
You do not need to put .ajax() within a .submit() handler when you're already inside of the plugin's submitHandler function. That's the whole point of the submitHandler option... to replace the default submit handler of the form.
This is all you'd need....
submitHandler: function (form) {
$.ajax({
url: 'customer/PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
// $('#DivEmailContainer').html(result);
}
});
return false;
}
Also note that $(this).serialize is replaced with $(form).serialize() since this is meaningless inside the context of the submitHandler. The form argument is already passed into this function by the developer to represent the form object.
If you're using the unobtrusive-validation plugin, then you cannot call .validate() yourself since unobtrusive already handles it for you. In other words, the jQuery Validate plugin only pays attention to first time the .validate() method is called, so if your instance is subsequent, then it's ignored along with your options.
Yes I know there is so many question like mine, I looked all questions and answers but The solutions is given didn't help me.
I tried to post log-in information to a controller. I got http-200 but ajax success function doesn't called. Instead error function is calling back but it doesn't give a specific error message.
My button code:
<button id="loginButton" type="submit" class="btn btn-success pull-right" onclick="login()">Giriş</button>
My javascript code:
function login ()
{
var Name = $("#userName").val();
var Pssword = $("#userPassword").val();
var user =
{
'userName': Name,
'userPassword': Pssword
};
jQuery.ajax
({
type:"POST",
url:"http://localhost:8080/Login/CheckUser",
dataType: 'html',
data: user,
cache: false,
success: function() {
alert("hadi ya");
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
}
And my controller code:
public function CheckUser()
{
$data = $this->input->post();
$result = $this->LoginModel->CheckUser($data); //returns 1 or nothing
echo $result;
}
And my model code:
function CheckUser($data)
{
$this->db->where('userName', $data['userName']);
$this->db->where('userPassword',$data['userPassword']);
$query = $this->db->get('users');
if($query->num_rows == 1)
return TRUE;
else
return FALSE;
}
I spent whole day for this, What I am doing false?
/* Change few of your lines: */
<button id="loginButton" type="submit" class="btn btn-success pull-right" onclick="login(event)">Giriş</button>
AND
function login (e)
{
e.preventDefault();
var Name = $("#userName").val();
var Pssword = $("#userPassword").val();
...
and further remains same.
I have a view that renders a partial view.
Index.cshtml contains a partial view.
The div below exist in the partial view
<div id="sa-da">
<input type="checkbox" id="selectAll"/><span>#T("Select / Deselect all invoices")</span>
<div class="payinvoices"><input class="amebtn" id="PayInvoices" type="button" text="Pay Invoices" onclick="RemovePagination();"/> </div>
</div>
I am using the method below to turn off pagination on a grid(webgrid) in the partial view with the use of a click of a button
function RemovePagination()
{
UpdateGrid("","clkPayInv");
$('#invoicestatus').val('unpaid');
SelectAllCheckboxesOnLoad();
}
I want the function below to select all the checkboxes on the click of the button as well
function SelectAllCheckboxesOnLoad()
{
var aa= document.getElementsByTagName("input");
for (var i =0; i < aa.length; i++){
if (aa[i].type == 'checkbox')
aa[i].checked = true;
}
}
?? The checkboxes are checked on the click of the button but it does not remain checked.
It just flickers for a second showing all the boxes checked and then it disappears.
How can I fix this?
function UpdateGrid(searchString,whatWasClicked) {
$jq.ajax({
url: '#Url.Action("Invoices")',
type: "GET",
cache: false,
data: { status: $("#invoicestatus").val(), from: $("#from").val(), thru: $("#to").val(), search: searchString, payInvClickBtn:whatWasClicked},
dataType: "html",
global: false,
error: function (jqXHR, status, error) { if (jqXHR.status == 401) { window.location.replace(location.href); } } ,
success: function (result, status, hr) {
$('#Grid').html(result);
}
});
}
The problem occurrs because your ajax call isn't completed at the time you trigger the check/uncheck.
Place the call to
SelectAllCheckboxesOnLoad();
inside the success method, after
$('#Grid').html(result);
<% Html.Grid(Model.InnerModel.ParamaterDetails)
.Empty("No data available")
.Columns(column =>
{
column.For(x => x.MinValue).Named("Possible Min Value");
column.For(x => x.MaxValue).Named("Possible Max Value");
column.For(x => x.ScoreValue).Named("Bespoke Score Value");
column.For(x => "<input type='button' name='button' class='btn' id='editOpenDialog' value='Edit' onclick=javascript:editParametersDialog('" + x.ID + "'); />").DoNotEncode();
}).Render(); %>
<%Html.EndForm(); %>
<script type="text/javascript">
function editParametersDialog(ID) {
// Go back to the server and get the data for the road card timetable
$.ajax({
url: "GetDetails",
type: "POST",
data: "ID=" + ID,
dataType: "json",
success: function(data) {
UpdateEditDialog(data);
$('#addEditDialog').dialog('open');
},
error: function(jqXHR, textStatus, errorThrow) { alert(jqXHR); alert(textStatus); }
});
}
function UpdateEditDialog(data) {
$("#MinValue").val(data.MinValue);
$("#MaxValue").val(data.MaxValue);
$("#ScoreValue").val(data.ScoreValue);
}
$(document).ready(function() {
});
</script>
GetDetails above is in controller
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetDetails (int ID)
{
// some code here
}
The onclick call javascript:editParametersDialog does not work. It does not get evoked.
Any clues what I might be doing wrong.
I can figure out that javascript:editParametersDialog does not turn BLUE which is normally the case.
<div id="addEditDialog" ></div>
your code is ok but u didn't put
<div id="addEditDialog"></div>
in the .aspx page.
for show dialog box div tag is must.
$('#addEditDialog').dialog('open');
using this code you say div tag is show as popup.
Do it and try this one again.