Calling validate function on button and getting the result (true/false) - jquery-validate

I am trying to do following task:
$("#btn1").click(function(){
var success = $("#myFrm").validate();
if (success == true) {
// post form through ajax
}
else{
// set focus on first field
}
});

I think you're looking for the valid() method:
$("#btn1").click(function(){
var success = $("#myFrm").valid();
if (success == true) {
// post form through ajax
}
else{
// set focus on first field
}
});
This assumes, of course, that you've configured jQuery validate on the form in question (using $("#myFrm").validate()).

Related

Prestashop 1.7.8 form fields validation

How to add custom class for example "error" to requiered fields when customer forget to fill them?
For example in registration form. When customer forget to fill multiple fields and click on Submit how to highlight all that missing fields?
Not a pretty solution, but it works
$('#login-form').submit(function() {
var $inputs = $('#login-form :input');
let hasError = false;
$inputs.each(function() {
if(!$(this).val() && $(this).prop('required')){
$(this).addClass('required-error-class');
hasError = true;
}
});
if(hasError){
return false;
}else {
return true;
};
});
A nicer solution is to use e.preventDefault and ajax

Redirection to other page after ajax request

I have a form that i use to add data to my database. I am using Ajax.BeginForm() to post data to the controller and then execute a stored procedure to save data. The result that i want is to show an error if the stored procedure fail to add data and to redirect to an other page in the other case. So I did something like this in my controller.
if (succees)
{
return RedirectToAction("ModificationPage", new { id = posted.articleId });
}
else
ViewData["ErrorMessage"] = msg;
return PartialView("_error");
_error is a simple partialview which display the error message. My problem is that when the stored procedure add data, instead of redirecting to the modification page, the modification page is rendred inside the view. Is there a method in asp mvc that can fix this
You can use onSuccess parameter of ajaxForm
using( Ajax.BeginForm( "action","controlle",
new AjaxOptions( ) {
OnSuccess = "mySuccessFunction",
} ) ) }
And then in js
function mySuccessFunction(){
//check if html with error exist on page
window.location = "url"
}
RedirectToAction is not supported in ajax. You could send the redirect URL back to the client and from the client use window.location to redirect to the new location.
you can in your controlleur
if (succees)
{
Redirect("/AREA/ContolleurName/ModificationPage/?Id=" + posted.articleId+ ")
}
else
ViewData["ErrorMessage"] = msg;
return PartialView("_error");**strong text**
and create action in your conrolleur
public ActionResult ModificationPage(int Id)
{
return //your view
}
Or ajax like this
$("class(.test) or Id (#Test)").on("click", function () {
var id = $(this).attr('id');
/*Création de la chaine en Json...*/
window.location.href = "/AREA/ContolleurName/ModificationPage?Id=" + id +"";
});

Create New Form not reload after save

working good in crm 2011 but not in crm 2013 online
On opportunity Entity create New record form i show only:
1.Some attributes(all other fields/Section/Tabs are hide on form)
2.and an Html button like
function OnFormLoad(){
if(Xrm.Page.ui.getFormType() == 1 ) {
SetRequiredLevelToNone();
createHtmlButton("Save");
HideTabsAndSections()
}
else {
}
}
On click of Html button following function is triggered.
function showWholeForm() {
Xrm.Page.data.entity.save();
}
I want to show all the fields of form after save, means want to reload whole form.
As working in crm 2011
The save method in CRM 2013 will not refresh the page anymore. The new refresh method should be used in this case, as follows:
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
save: Boolean value to be passed as true if data should be saved
after it is refreshed.
successCallback: Function to call when the operation succeeds
errorCallbak: Function to call when the operation fails, that will be passed an object with 2 properties - error code (number) and localized error message (string)
You could find the method documented here: http://msdn.microsoft.com/en-us/library/dn481607(v=crm.6).aspx
I think you should first disable the auto-save if you want consistency with CRM 2011.
function OnSaveDisableAutoSave(eventArgs) {
var saveType = eventArgs.getEventArgs().getSaveMode();
if (saveType == 70 ||saveType == 2)
{ //Disable AutoSave
eventArgs.preventDefault();
}
}
and then
function showWholeForm() {
Xrm.Page.data.refresh(true).then(successCallback, errorCallback);
}
To fix this you can do:
var saved = false;
function onLoad(){
checkIfFormShouldBeReadOnly();
attachEvent();
}
function attachEvent() {
Xrm.Page.data.entity.addOnSave(executeOnSave);
}
function executeOnSave(saveExecution) {
if (!saved) {
saved = true;
Xrm.Page.data.save().then(
function () {
checkIfFormShouldBeReadOnly();
},
function (errorCode, message) {
Xrm.Page.data.refresh();
}
);
}
}

Mvc Ajax Jquery Not refreshing view on post

I am new to ajax and mvc... i have a problem with posting back data from jquery. The problem I have is the values are being populated the controller is hit database is updated and then it returns to the page with old data it is not refreshing I have to click f5 to see changes what am I doing wrong? Thanks in advance
Jquery
var values =
{
"PagePartIdentifier": element,
"PagePartContent": data
}
$.post(#Html.Raw(Json.Encode(Url.Action("UploadData", "Home"))),values,function(data)
{
// do stuff;
});
Model
public class PagePartModel
{
public string PagePartIdentifier { get; set; }
public string PagePartContent { get; set; }
}
Controller
[HttpPost, ValidateInput(false)]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UploadData(PagePartModel pagePartm)
{
UpdatePage(pagePartm);
ModelState.Clear();
//return RedirectToAction("Index");
return Json(new { success = true });
}
Html is rendered from a helper method
public static PagePartModel PageAfterContent(this System.Web.Mvc.HtmlHelper html, int page)
{
string part = "AfterContent";
Blog.PageParts pageParts = new Blog.PageParts();
PagePartModel thispart = pageParts.GetContentForPageByPart(page, part);
return thispart;
}
Returns the model for each part to the page
When using $.post, you're sending the data to the server via ajax, so the page never reloads. I'm not sure what the UpdatePage(pagePartm); call in your post method is doing, but since that method is getting called with ajax, it can't change anything on the page. Now in your success handler on your $.post, you can manipulate the DOM to reflect the success or failure of your $.post call.
In your action, instead of returning your Json(new { success = true }); you should/could return the data that you want to be displayed on the page,
e.g.
return Json(new { pagePartm }); // if that is what should be returned
Then modify your $.post() to append the data into the DOM somewhere.
e.g.
$.post("your_controller_action", { name: "John", time: "2pm" },
function(data){
doStuff(data); // this is your point of interaction with the returned data
// or
$("#my_h3").val(data.pagePartm.PagePartIdentifier);
$("#my_div").append(data.pagePartm.PagePartContent);
});
from the jQuery.post documentation.
This will avoid the need to refresh the page to see the results.
jquery ajax post cache property is false ?
$.ajax({
url: '/youraction',
cache: false,
type: 'post'
success: function (data) {
},
error: function (e) {
alert(e.responseText);
}
});

ASP.NET MVC "Ajax.BeginForm" executes OnSuccess even though model is not valid

I have a "submit feedback" form which uses "Ajax.BeginForm" to render a partial containing the form elements. The OnSuccess event is triggering even if the ModelState is not valid. Is this normal? I was expecting to be able to do a few postbacks resulting in an invalid model, then when the model is valid and there are no errors then the OnSuccess event would trigger?
I handle this issue with a fairly simple javascript technique:
First setup your OnSuccess like this:
OnSuccess = "UpdateSuccessful(data)"
Then your javascript function like this:
function UpdateSuccessful(data) {
if (data.indexOf("field-validation-error") > -1) return;
// Do your valid stuff here
}
This way, there is no need to mess with your controller, or more importantly, your controller can return the Partial View with the model errors without doing anything weird, ie:
public ActionResult SaveDetails(Project model)
{
if (ModelState.IsValid)
{
model.SaveProject();
}
return PartialView("ProjectForm", model);
}
And in your AjaxOptions:
UpdateTargetId = "FormContents"
Now just make sure you have a div or something with id="FormContents" wherever you want your form displayed.
Is this normal?
Yes, of course. If the server sends HTTP 200 the OnSuccess method is called. The notion of modelstate validity is server side only. As long as your controller action returns some view/partial/json/... the OnSuccess will trigger. If an exception is thrown inside your controller action then the OnError will be triggered instead of OnSuccess.
So in order to handle this case you could have your controller action do something along the lines of:
[HttpPost]
public ActionResult Process(MyViewModel model)
{
if (!ModelState.IsValid)
{
return Json(new { success = false });
}
return Json(new { success = true });
}
and then:
function success(result) {
if (result.success) {
// the model was valid
} else {
// the model was invalid
}
}
Now in the case of invalid model you might want to show the error messages to the user by refreshing the form. What you could do in this case is place your form inside a partial and in the event of an invalid modelstate you would return a partialview from your controller action and in the case of success a json object. So in your success handler you could test:
function success(result) {
if (result.success) {
// the model was valid
} else {
// there were errors => show them
$('#myform_container').html(result);
// if you are using client side validation you might also need
// to take a look at the following article
// http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
// and reattach the client validators to the form as you are
// refreshing its DOM contents here
}
}
You can do the following:
var OnSuccess = function() {
if ($(".validation-summary-errors").length == 0) {
//Your javascript/jquery code goes here
}
}
Slight variation on Luis' answer:
function OnSuccess() {
if ($("span[class='field-validation-error']").length == 0) {
alert("Target Platform saved Successfully.");
}
}
I return a bad request instead of the View to ensure that the ajax call returns onfail and not onsuccess.
In the xhr.statustext you can find the string written in the bad request and manage correctly the onfail event.
Server side:
if (!ModelState.IsValid)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Model not valid");
}
Client side:
$.ajax({
url: '',
method: 'POST'
}).fail(function (xhr) {
alert(xhr.statustext);
});

Resources