Call a Function After MVC's Remote Validation - javascript

I want to call a function after MVC's Remote Validation returns true. But looks like I need another event to call that function. I have tried to call onchange on same datepicker element but they are not called in the right sequence. I want to call validation first and myFunction later.
P.s. I have also gone through jquery.validate invalidHandler but that doesn't seem to solve the problem. As it also needs some event call.
<span class="fgroup">
#Html.TextBoxFor(model => model.master.D1, new { #id = "datepicker" })
#Html.ValidationMessageFor(model => model.master.D1, "", new { #class = "text-danger" })
</span>
Here is my function that I want to call after Remote Validation returns true:
function myFunction1() {
var datVal = $("#datepicker").val();
var url = "/TrM/AutoDocNoGen?date=" + datVal;
$.ajax({
data: datVal,
type: "GET",
url: url,
success: function (data) {
var formValid = $("#allSaveForm").validate().form();
if (!formValid) {
return false;
}
$(".vchrNoField").val(data.NewValue);
},
error: function () {
}
}); }
After return from the Ajax call I want to update the value of this field. Its very important that the validation is called first and this field below is updated afterwards.
#Html.EditorFor(model => model.master.S1, new { htmlAttributes = new { #class = "text-input-grey vchrNoField" } })

I have successfully resolved the issue by using Jquery's ajaxComplete method. It bothered me a lot until I resolved it. Here is what I have done.
$(document).ajaxComplete(function (event, xhr, settings) {
if (settings.url === "/Rules/datecheck" && xhr.responseJSON == true) {
var datVal = $("#datepicker").val();
var ur = "/TrM/AutoDocNoGen?date=" + datVal;
$.ajax({
data: datVal,
type: "GET",
url: ur,
success: function (data) {
$(".vchrNoField").val(da.NewValue);
},
error: function () {
}
});
}
});
So basically I have called my ajax request on ajaxComplete and adding an if statement to check if the response from the remote validation is returned true. And Tada! Its Done!

Related

Datepicker is not a function after ajax request

I'm writing simple search engine in Lumen framework.
I have a list of status for example. The user can get one of status from the list and after click search button then in the page, I need to load data with chosen status.
One of the element is datepicker. And this datepicker work great when I refresh the page or go to the page by GET method. But I have a problem when I go on the page by POST method from my click "SEARCH". There is some code from my view where I get status from the list and pass to my controller action:
<script type="text/javascript">
jQuery(document).ready(function ($) {
var clientId = null;
var status = null;
$("[name='deadline']").datepicker(); //there I have this error comunicat
$('#clients').on('change', function () {
clientId = $(this).val();
});
$('#statuses').on('change', function () {
status = $(this).val();
});
$('#searchForPremium').on('click', function () {
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
})
});
</script>
And there is controlelr action:
public function clientsPremium()
{
$premiumTexts = NULL;
$premiumClients = \App\Text::getPremiumClients();
$premiumTexts = \App\Text::getPremiumTexts();
$statuses = \App\Text::getStatus();
if (Request::isMethod('get')) {
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts]);
}
if (Request::isMethod('post')) {
$clientID = Request::get('client_id');
$statusName = Request::get('status');
if ($clientID != NULL) {
$premiumTexts = $premiumTexts->where('text.client_id', $clientID);
}
if ($statusName != NULL) {
$premiumTexts = $premiumTexts->where('text.status', $statusName);
}
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return response()->json(view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts])->render());
}
}
Then I have error "Uncaught TypeError: $(...).datepicker is not a function...". I cant understand how it is work and why I got this message. It appear only when I click to search button.
It is $('body').empty().html(data); or my controller action:
return response()->json(view('admin.clients-premium', ['copywriters' => $copywriters, 'statuses' => $statuses, 'positioners' => $positioners, 'clients' => $premiumClients, 'texts' => $premiumTexts, 'allowedTemplates' => $allowedTemplates, 'section' => 'clients.premium'])->render());
I tried to use $.noConflict(); but there is no effect for me. Can anyone look at my code and try to help me what should I change? I think my return "response()->json(view..." reload all page and get my jquery-ui multiple time. But I can wrong. Can anyone help me?
Reinitialize it after you change content from ajax response.
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$("[name='deadline']").datepicker();
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
After ajax success destroy the datepicker and reinitialize it as below:
$('body').empty().html(data);
$("[name='deadline']").datepicker("destroy");
$("[name='deadline']").datepicker();
you clear entire body so may be possible you include js css in body so please add and remove this div instead of entire body and if you add dynamic datepicker to any text box please use
$("[name='deadline']").datepicker(); on ajax response .

event.preventDefault() and redirect asp mvc/jQuery

What am trying to do is to post on form submit to a action and catch response and that works fine.Problem is when RedirectToAction gets called, it just stays on that same view(it doesn't redirect),or in case model is not valid, it doesn't show model validation. So i guess the problem is with url, but how can I correct it?
jQuery
$("form").on("submit", function (e) {
e.preventDefault();
var form = $(this);
var formURL = form.attr("action");
$.ajax({
type: "POST",
url: formURL,
data: $(this).serialize(),
success: function (response) {
if (response !== null && response.success == false) {
alert(response.responseText);
}
}
});
});
c# asp mvc
public ActionResult Add(SomeModel model) {
if (ModelState.IsValid) {
if (true) {
return Json(new { success = false, responseText = "Some error" }, JsonRequestBehavior.AllowGet);
}
return RedirectToAction("Details", new { id = id });
}
//gets called but it doesn't show validation.
return View(model);
}
public ActionResult Details(int id) {
//gets called but it doesn't show the view.
return view(model);
}
Because you're posting your form with an Ajax POST and your in your success function you have alert(response.responseText), you are NOT going to receive a View.
What you need to do is in success function, take the response from Details action and place it inside an HTML element on the page. Like below:
success: function (response) {
$("#div").html(response);
}
On another note, since you're not using a standard FORM and your posting with JavaScript, you wont get built in validation the models provide.

Pass data from Row into Javascript function

I have a button in a webgrid row defined as such:
grid.Column("Fault", header: "Fault", format: (item) =>
{
if (item.Fault != null)
{
return new HtmlString(string.Format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault.Message));
}
return "";
}))
This is my ShowFaultMessage function:
function ShowFaultMessage(message) {
$.ajax({
url: '/Home/Message/',
data: message,
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
var w = window.open("/Home/Message", "Fault Message", "width=400, height=400");
$(w.document.body).html(result.responseText);
}
});
};
This is not working though. I know that item.Fault is correct because my If Block works in the column definition. But when I click the button, it throws an undefined reference exception. How can I make this work. I am new to MVC, but something like this is really easy with xaml. I refuse to believe it's not possible in razor/mvc.
EDIT: This is my action method for loading the popup window view:
public ActionResult Message(string faultMessage)
{
var model = new MessageViewModel { Message = faultMessage };
return View(model);
}
Also edited my other code blocks to show their current state.
Rewrite the return to be something like this
return new HtmlString(string.format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault));
You need to use the string.format to insert the value into the string

Ajax function not being hit in submitHandler

Form validation works, but I can't get the Ajax call to fire correctly. The submitHandler is being reached, but the Ajax call isn't. I have included a Fiddle at the bottom, but obviously you can't fire ajax calls from there.
$(".player-code, .submit").hide();
//VALIDATION
$(function () {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function () {
var accountNumber = $(".accountNumber").val();
var domain = $(".domain").val();
var playerClass = $(".playerClass").val();
var dataString = accountNumber + playerClass;
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$(".player-code").show();
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
},
failure: function () {
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
}
});
});
jQuery.validator.addMethod("domainChk", function (value, element, params) {
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
}, "Valid hostname required for player code");
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
$('input[type="text"]').on('click keyup blur', function () {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
//PREPOPULATE ACCOUNT FROM QUERY STRING
var url = window.location.href;
var regex = /=.*/; // match '=' and capture everything that follows
var accountId = url.match(regex);
$(".accountNumber").val(accountId).remove("=");
//
jsFiddle: Link
There is no failure: option for $.ajax(). If you want to see any errors that happen in the ajax call, then use error: to capture the error.
To make form submit you should use
<button class="btn btn-default submit" type="submit">Submit</button>
instead of <div class="btn btn-default submit">Submit</div>
submitHandler will be called only on native form submit.
Fiddle

jquery validation not working in partialview?

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.

Categories