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.
Related
I have this search bar inside navigation file and it's an enter submit input tag.
I include this file in many pages. but when I enter(submit) it doesn't go to searchResults.blade.php
MY HTML
<input class="searchkey" id="searchkey" type="search" required onkeydown="search(this)">
My JS
$('.searchkey').keydown(function(event) {
var getKeyword = document.getElementById("searchkey").value;
if (event.keyCode == 13) {
$.ajax({
url: "search",
type: "POST",
data:{
getKeyword : getKeyword
},
success: function() {}
});
}
});
MY CONTROLLER
public function multiSearch()
{
$searchKey = Input::get('getKeyword');
$getResults = array();
$getResults = DB::select("SELECT title FROM books WHERE title LIKE '%$searchKey%'");
return View::make('content.searchResults',array('getResults'=>$getResults));
}
MY ROUTES
Route::post('search', 'UserController#multiSearch');
First of all in your ajax callback you should put the view results in some container on the page, i.e.: <div id="search-result"></div> by adding this callback function:
success: function(data) {
$('#search-reasult').html(data);
}
You also have to render the view in your controller like this:
return View::make('content.searchResults',array('getResults'=>$getResults))
->render();
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!
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
I've got a Spring MVC - JSP web application. Before submitting a specific form I need to fill a text value input with JS/jQuery so the form POSTed contains that info. This text value is the result of an ajax call that should be done when the submit button is clicked but before the form data is send to the controller.
The relevant pieces of code in my JSP are the following:
<script>
//Gets from model a new valid file code number
function getFileCodeNumber(res){
$.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: { department: $("#department").val(), docType: $("#docType").val() },
success: res,
error: function(){ alert('Error while request..');}
});
}
</script>
<script>
$(function() {
//Other JS code
$("#submitForm").click((function(event) {
if($("#chkLanguage").prop('checked')){
//some stuff
}else{
getFileCodeNumber(function(data){
//do some stuff with 'data'
});
}
}));
});
</script>
<form:form id="form" class="form-horizontal" method="post" action="AddDoc" commandName="document" enctype="multipart/form-data">
<div class="row" style="text-align:center;">
<input id="submitForm" type="submit" class="btn btn-primary btn-lg" name="commit" value="Finish">
</div>
</br>
</form:form>
Just to let you know, the ajax call works perfectly when called from another trigger action in the same JSP, but when called from the "click" function it retrieves an alert error but is shown on screen for less than 1 second and therefore I cannot tell you what does it say. By the way, Firebug throws "NS_ERROR_NOT_AVAILABLE: prompt aborted by user".
Note that I tried to replace "click" trigger for "submit" that happens exactly the same. My guess would be that the form is being submitted before the ajax call is completely done, but I expected "submit" and "click" functions to do the its job before POSTing the data.
Does anybody have a clue?
EDIT : I found out that the alert that I wasn't able to see is printing the error code of the ajax call. However, I've checked the controller's function that gives response to this call and I've seen it gets completed succesfully and retrieves the expected value. What's more, when I call this function from another trigger in the same JSP it works perfectly. Just to let you see the simple code in the controller:
#RequestMapping(value = "getFileCodeNumber", method = RequestMethod.POST, headers = "Accept=*/*")
public #ResponseBody
String getFileCodeNumber(#RequestParam(value = "department", required = true) String department,
#RequestParam(value = "docType", required = true) String docType) {
int n = cdocs.getNewCode(department, docType);
if (n == 0) {
return "EEEE";
} else {
char[] zeros = new char[4];
Arrays.fill(zeros, '0');
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
System.out.println(df.format(n));
return df.format(n);
}//END_IF
}//END_METHOD
Any ideas?
Try that:
function getFileCodeNumber(res) {
return $.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: {
department: $("#department").val(),
docType: $("#docType").val()
},
success: res,
error: function () {
alert('Error while request..');
}
});
}
$("#submitForm").click(function (event) {
event.preventDefault();
if ($("#chkLanguage").prop('checked')) {
//some stuff
} else {
getFileCodeNumber(function (data) {
//do some stuff with 'data'
}).done(function () {
$('#form').get(0).submit();
});
}
});
Instead of executing your javascript when the submitbutton is pressed, use a normal button and execute the submit function from the script.
You could do something like this:
function getFileCodeNumber(res){
$.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: { department: $("#department").val(), docType: $("#docType").val() },
success: res,
error: function(){ alert('Error while request..');}
})
}
$(function() {
if($("#chkLanguage").prop('checked')){
//some stuff
$("#form").submit();
}else{
getFileCodeNumber(function(data){
//do some stuff with 'data'
}).done(function(){
$("#form").submit();
});;
}
});
I am having strange behaviour when using jquery.on().
Basically, just trying to create a newsletter signup form (can be dynamically generated and not there on initial DOM load) and pass the details through in Ajax but it is not registering the first click on the submit button meaning that to successfully submit, the user has to click twice (only seeing the success message and 'subscribe' post on 2nd click).
The html:
<div class="newsletter-widget grid-item masonry-brick">
<input name="Email" type="email" placeholder="Please enter your email" required />
<input type="submit" value="Subscribe" class="newslettersubmit"/>
and the javascript (in document ready);
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
and the functions within an object that are called;
DD.newsletter = {
behavior: function (item) {
item.click(function (e) {
e.preventDefault();
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
});
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});
I've tried using 'click' as the action for on() but this registers an event on each click and i get thousands of forms submitted!
Any help appreciated!
Change the div container to a form element:
<form class="newsletter-widget grid-item masonry-brick">
You'll want to register the submit event to the form, not the input field. Here's a quick refactor of your form submission:
$(document).on('submit', '.newsletter-widget', function (e) {
e.preventDefault();
DD.newsletter.behavior(); //Submit the form via AJAX
});
If you wanted to hook this up to your behavior method, just unwrap the click:
behavior: function () {
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
}
The first click on the button will cause the behaviour click event handler to be bound to the button. Bind the behaviour directly instead of in the click event handler.
Replace this:
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
with:
DD.newsletter.behavior($('.newsletter-widget input[type=submit]'));
It should probably (I think) be something like this:
DD.newsletter = {
behavior: function (item) {
var where = $(item).parents('section').attr('id');
var email = $(item).siblings('[name$=Email]'),
var emailVal = email.val(); // why were you declaring this without 'var'?
DD.newsletter.subscribe(email, emailVal, where);
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});