Jquery Validate then .onsubmit function - html

I am using Jquery validation in a form and also an Ajax function in a .on(submit) code.
The problem is even when the validation is wrong the .on(submit) function still runs.
Is there any type of "if validation success" code to add to the validation code to put the .on(submit) code in so it will only run when the form is correct and validated?
this is the .on(submit) function
$('#valform').on('submit', function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo MAXINBOUND_PLUGIN_URL ?>/php/localProxy.php",
data: $('#valform').serialize(),
success: function (response) {
alert('Great!');
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
});
and this is the validation code
$("#valform").validate({
invalidHandler: function(form, validator) {
success: function (response) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("Please correct the required field(s)");
} else {
$("#error-message").hide();
}
},
messages: {
agree: {
required: ""
},
phone1: {
required: ""
},
address1: {
required: ""
},
},
rules: {
agree: {
required: true,
},
phone1: {
required: true,
phoneUS: true
},
Address1: {
required: true,
addr: true,
},
},
});

You can use submitHandler to do ajax calls. So it will call only after passing all validations.
$("#valform").validate({
submitHandler: function(form) {
//do ajax call
}
})

You can use the jquery valid() method to check if the submitted form is valid. Something like this...
if ($("#valform").valid()) {
// do your ajax stuff
}
Please note that valid() will work only when the validate() is called on the form prior to it.
Hope this helps!

Related

KendoGrid: can't disable autosync + all other lines are disabled after "destroy"

I tried so solve this for a while now, but cannot find the solution.
I cannot disable autosync for some reason. Everytime I click on "destroy" for a single row, transport.submit is triggered (and would send data to the server). I actually only want to trigger submit once, when I click the "save" button.
Is this expected behaviour? Should I handle the server communications externaly and only save locally in transport.submit? Or am I doing something wrong?
Once I remove one item using the "destroy" button, all other items are disabled until I press the "cancel" button.
How can I avoid this?
Here is my Code:
$(document).ready(function () {
var myData = getDataSource();
var dataGrid = $("#divOverview").kendoGrid({
dataSource: myData,
sortable: true,
filterable: true,
pageable: true,
toolbar: ["save", "cancel"],
columns: [
// Dataworld
{ field: "Dataworld", width: "180px" },
// Servername
{ field: "Servername"},
// IPAddress
{ field: "IPAddress"},
// Commands
{ command: ["destroy"], title: " ", width: "250px" }
],
editable: {
mode: "inline",
confirmation: false
}
});
});
function getDataSource(){
var datasource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax({
url: "../AccountSyncConfig/GetAccountSyncConfig.erb",
dataType: "json",
data: {mandatorID: mandatorID},
success: function(result) {
options.success(result);
},
error: function(result) {
options.error(result);
}
});
},
submit: function(e) {
var data = e.data;
console.log(data);
},
parameterMap: function(data, type) {
if (type == "read") {
return { mandatorID: mandatorID};
} else if (type == "submit") {
//console.log( {models: JSON.stringify(data.models)} );
return {
data: kendo.stringify({
mandatorID: mandatorID,
models: data.models
})
};
} else {
return "";
}
}
},
schema: {
model: {
id: "EntryID",
fields: {
Dataworld: {
type: "string",
validation: {
required: true
}
},
Servername: {
type: "string",
validation: {
required: true
}
},
IPAddress: {
type: "string",
validation: {
required: true,
IPAddressvalidation: function (input) {
if (input.val() != "") {
input.attr("data-IPAddressvalidation-msg", "Ungültige IP-Adresse");
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(input.val());
}
return true;
}
}
}
},
}
},
autoSync: false,
batch: true,
pageSize: 10
});
return datasource;
}

Displaying JSON

I am returning JSON from my controller to AJAX success response. The JSON look likes:
{
"success": false,
"errors": {
"ConfirmPassword": [
"'Confirm Password' and 'Password' do not match.",
"Password does not meet the criteria.",
"The Confirm Password must be at least 6 characters long."
],
"Password": [
"Password does not meet the criteria.",
"The Password must be at least 6 characters long."
]
}
}
Now I wan to display data in div tag with formatting. I have tried :
$('#info').append(JSON.stringify(data));
but this is just a dump of whole string, which doesn't look nice in my view. Any idea how to do it.
Ajax call :
$.ajax({
type: 'POST',
url: '/Dashboard/UpdatePassword/',
data: $("#password-update-form").serialize(),
success: function (data) {
if (data.success) {
//alert("test");
}
else {
$('#info').append(JSON.stringify(data));
}
Thanks for all replies. I managed to sorted it.
success: function (data) {
if (data.success) {
alert("test");
}
else {
console.log(JSON.stringify(data.errors))
for (var prop in data.errors) {
//alert(prop + " is " + data.errors[prop]);
$('#val-form').append('<p>'+data.errors[prop]+'<p>');
}

No HTTP resource was found that matches the request URI 'http://localhost:xxx:

I am working on .net web api.....
Web Api Config :
public static void Register(HttpConfiguration config)
{
// Verb Routing
RouteTable.Routes.MapHttpRoute(
name: "SmallBizApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
action = RouteParameter.Optional
}
);
config.Formatters.Clear();
config.Formatters.Insert(0, new SmallBiz.WebAPI.Common.JsonpFormatter());
}
I am using jsonp format to load data in kendo-ui Gantt chart as can be seen...
<div id="grid"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
var projectdata = "http://localhost:1799/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: projectdata + "/project",
dataType: "jsonp"
},
update: {
url: projectdata + "/project/put",
dataType: "jsonp"
},
destroy: {
url: projectdata + "/project/delete",
dataType: "jsonp"
},
create: {
url: projectdata + "/project/post",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProjectId",
fields: {
ProjectId: { editable: false, nullable: false },
Name: { validation: { required: true } },
Status: { validation: { required: true } },
IsActive: { type: "boolean" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: ["create"],
scrollable: false,
sortable: true,
groupable: true,
columns: [
{ field: "Name", title: "Project Name", width: "170px" },
{ field: "Status", title: "Status", width: "110px" },
{ field: "IsActive", title: "Active", width: "50px" },
{ command: ["edit", "delete", "Setting","Task"], title: " ", width: "150px" }
],
editable: "popup"
});
});
</script>
Controller code :
public IQueryable<ProjectsDM> GetProject()
{
return db.Project;
}
[HttpPut]
public IHttpActionResult PutProjectsDM(int id, ProjectsDM projectsdm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != projectsdm.ProjectId)
{
return BadRequest();
}
db.Entry(projectsdm).State = EntityState.Modified;
try
{
projectsdm.ModifiedBy = "adnan";
projectsdm.ModifiedDate = DateTime.Now;
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectsDMExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Get method/action is working fine in kendo grid but i face problem
with put method/action(when we try to edit some record in grid)....
The errors in firebug .net tab
Response : "Message": "No HTTP resource was found that matches the
request URI 'http://localhost:1799/api/project
/put?callback=jQuery191012879030621062526_1433486934717&models=[{\"ProjectId\":2%2C\"ClientId\":1%2C
\"FirmId\":1%2C\"Status\":\"Started\"%2C\"Name\":\"Flexi77\"%2C\"IsActive\":true%2C\"CreatedDate\":\"2015-06-03T00
:00:00\"%2C\"ModifiedDate\":\"2015-06-03T00:00:00\"%2C\"CreatedBy\":\"adnan\"%2C\"ModifiedBy\":\"adnan
\"}]&_=1433486934719'.",
> "MessageDetail": "No action was found on the controller 'Project'
that matches the name 'put'."
json : "No action was found on the controller 'Project' that matches
the name 'put'."
Is there some route error or stupid mistake, please do help....
any kind of hint/help is much appreciated....
thanks for your time
The problem is that your Web API action expects two parameters:
int id, it's missing from the request URL
ProjectsDM projectsdm, can be retrieved from the payload (request body)
You need to use an URL that includes the missing id parameter. In the route template it's optional, but, if it's missing, as the action which requires it, the action cannot be chosen by the action selector.
So either add the id to the URL, or remove the id parameter from the action.

Kendo UI Scheduler and ASP.NET MVC

Trying to make work Kendo UI with ASP.NET MVC.
I can use ready-to-work toolkit, but it will tie front-end to back-end; that's inappropriate, so I'm doing all manually.
I've bound datasource
dataSource: {
batch: true,
transport: {
read: {
url: "http://192.168.0.34/FRINGE/api/tasks",
dataType: "json"
},
modified schema
schema: {
model: {
id: "TaskID",
fields: {
taskId: { from: "TaskID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start" },
end: { type: "date", from: "End" },
description: { from: "Description" },
ownerId: { from: "OwnerID", defaultValue: 1 },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
},
parse: function (responce) { /*debugger;*/ }
},
and wrote a simple controller
[HttpGet]
public ActionResult Tasks(int? id)
{
//«data» type is List<Tasks>
if (id.HasValue)
return Json(data.SingleOrDefault(x => x.TaskID == id.Value), JsonRequestBehavior.AllowGet);
else
return Json(data, JsonRequestBehavior.AllowGet);
}
Which produces data like
[{"TaskID":1,"Title":"Action","Start":"\/Date(1425009600000)\/","End":"\/Date(1425013200000)\/","Description":"Action time","OwnerId":1,"IsAllDay":false},{"TaskID":2,"Title":"Dinner","Start":"\/Date(1425034800000)\/","End":"\/Date(1425038400000)\/","Description":"Dinner time","OwnerId":1,"IsAllDay":false}]
But nothing works. Checked schema and data on Telerik Kendo UI Dojo, and all good there. I think, problem in controller declaration due to some params lack.
What I've missed?
You're defining a parse method in your schema which does nothing. You have to remove it or return data from it:
parse: function(response) {
return response;
}

Web API Odata not returning correct metadata

I'm using OData v4 with Web API to communicate with my AngularJS web application.
More specifically I'm trying to display my data using Kendo UI Grid.
My problem is, that my Web API does not return the correct metadata, resulting in Kendos datasource not being able to display the data.
I'm doing paging, and to do that I need the "count" property in my response for Kendo UI Grid datasource to be able work properly.
The response I'm expecting the Web API should look something like this:
http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940644
However, the result I'm seeing in the response is:
{
"#odata.context":"http://localhost:1983/odata/$metadata#TestReports","value":[
{
"Id":1,"Name":"Test Testesen","Purpose":"Kendo UI Grid Test","Type":"Rumraket","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":2,"Name":"Gunner Testesen","Purpose":"OData Web API Test","Type":"Sutsko","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":3,"Name":"Bertram Didriksen","Purpose":"Server Paging Test","Type":"Flyver","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":4,"Name":"Oluf Petersen","Purpose":"Test","Type":"B\u00e5d","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":5,"Name":"Alfred Butler","Purpose":"Opvartning","Type":"Batmobil","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
}
]
}
My code for retrieving the data is:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "odata"
},
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
console.log(paramMap);
delete paramMap.$inlinecount; // <-- remove inlinecount parameter
delete paramMap.$format; // <-- remove format parameter
console.log(paramMap);
return paramMap;
}
},
schema: {
data: function (data) {
return data; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.length; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
My WebApiConfig class is corrently like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata",
model: GetModel()
);
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<TestReport>("TestReports");
return builder.GetEdmModel();
}
}
Does anyone have any suggestions on how I get the Web API to return the correct metadata?
Apparently Kendo UI Grid is not supporting OData v4.
The fix was to modify the parameterMap of the Kendo datasource, and tell it to use $count instead of $inlinecount.
Besides that I had to tell the schema to read "#odata.count" as the "total" value.
After I edited the before posted code to the ode below, I got the correct data in my response:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "json"
},
parameterMap: function (options, type) {
var d = kendo.data.transports.odata.parameterMap(options);
delete d.$inlinecount; // <-- remove inlinecount parameter
d.$count = true;
return d;
}
},
schema: {
data: function (data) {
return data.value; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data['#odata.count']; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};