Custom Validation not working with Ajax MVC Call - asp.net-mvc-3

On the click of a button i want to sumbit a form if another form, in the same page (not a ligthbox) is valid. That validation is a Custom Validation I created and is working fine.
This is the code in the view
$("#btnSave").click(function (e) {
if ($("#GeneralButtonFrm").valid()) {
$("#ButtonFrm").submit();
} else {
//Error Message
} });
The problem is that the submit action is executing without waiting for the response of the custom validation which return false.
Any idea why this is happening?
Note: I said I am not using a ligthbox rendering a partial becouse in that case the solution would be jQuery.validator.unobtrusive.parse('#form');
Thanks

You are still very vague, in your question. But i think what you want is to call ajax and do a serverside validation. If so, the problem is that your validation will return before ajax request since the ajax request is async.. Do this
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
jQuery.validator.addMethod("ajaxCustom", function (value, element) {
var wrap = $(element);
var url = wrap.data("customAjaxUrl");
var result;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function (data) {
result = data.valid;
},
data: { value: value, id: element.id },
async: false
});
return this.optional(element) || result;
}, "Ajax");
$.validator.unobtrusive.adapters.addBool('ajaxCustom');
</script>
<style type="text/css">
.input-validation-error {
background: red;
}
</style>
</head>
<body>
<form action="/">
<input data-val-ajaxCustom="Tuckel" data-val="true" data-val-required="Its required" data-custom-ajax-url="validate.html" />
<button type="submit">Submit</button>
</form>
</body>
</html>

Related

How to call a controller function when someone click on a check box in laravel 8

is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>

Kendo Vue datasource for Kendo grid with Auth Header

I am trying to create a datasource for a Kendo Grid in Vue.js. I need to put auth headers so declarative syntax in the template does not fix my problem.
The link below makes it possible for an array, but I need an example with an AJAX call or a promise (an Axios one would be perfect).
Kendo UI Grid Data variable Vue.js
A much cleaner answer came from Telerik support today. It make the world a better place :)
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-vue-ui/wrappers/dropdownlist/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1018/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1018/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1018/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.3.1018/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1018/js/kendo.all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/#progress/kendo-all-vue-wrapper/dist/cdn/kendo-all-vue-wrapper.min.js"></script>
</head>
<body>
<div id="example">
<div id="app" class="demo-section k-content">
<h4>Find a product</h4>
<kendo-datasource ref="datasource"
:type="'odata'"
:server-filtering="true"
:transport-read="{ url: 'https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products', beforeSend: onBeforeSend }">
</kendo-datasource>
<kendo-dropdownlist ref="dropdownlist"
:data-text-field="'ProductName'"
:filter="'contains'"
:auto-bind="true"
:data-source-ref="'datasource'">
</kendo-dropdownlist>
</div>
</div>
<style>
.demo-section .k-dropdown {
width: 100%;
}
</style>
<script>
new Vue({
el: '#app',
methods: {
onBeforeSend: function(xhr) {
var token = "asd81237hdbsjkfh234uygr38fg73";
xhr.setRequestHeader('Authorization', 'Bearer ' + token)
}
}
})
</script>
</body>
</html>
Ok, so the documentation is a bit flaky, but I managed to get a custom function going in Vue, just like in the plain Kendo UI datasource. Look at this demo for reference: http://dojo.telerik.com/uXELIh
This is a mix of declarative and custom methods, so it might look a bit odd. (I've never worked with the VUE wrapper before)
Instead of the transport-read-url="uri/to/somewhere" property just define a transport-read="readData" property.
<kendo-datasource ref="datasource1"
:transport-read="readData"
:schema-model-id="'ProductID'"
:schema-model-fields="schemaModelFields"
:batch='true'
:page-size='20'>
</kendo-datasource>
Then create the readData method:
new Vue({
el: '#app',
data: {
schemaModelFields: {
/*...*/
}
},
methods:
readData: function(e) {
//this simply returns one Product with a name Chai as a dummy
//set your Auth headers here, do the request and then pass
//the data in the e.success method as a parameter
e.success({ProductName: "Chai"})
}
}
/*...*/
});
That's all there is.
However If you have an Auth header, that you need to prepend to all your ajax requests, I'd suggest you use $.ajaxSetup() (How can I add a custom HTTP header to ajax request with js or jQuery?). This will save you the hassle of implementing this for read, update, create and delete, each and every time.
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
A bit painful but I was able to do it with Marco's help
Here is the code
<template>
<div>
<kendo-datasource ref="datasource1"
:transport-read="readData"
:batch='true'
:page-size='20'>
</kendo-datasource>
<kendo-grid :height="550"
:data-source-ref="'datasource1'"
:pageable='true'>
</kendo-grid>
</div>
</template>
<script>
export default {
name: 'grid',
computed: {
token () {
return this.$store.state.access_token
}
},
methods: {
readData: function (e) {
console.log(this.token)
var tkn= this.token
$.ajax({
url: 'http://127.0.0.1/AssetExtranet.WebAPI2/api/Vw_Hmn_Branch',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tkn)
},
dataType: 'json',
success: function (data) {
e.success(data)
},
type: 'GET'
})
}
}
}
</script>
Thank Marco and Vue is perfect and super fast. It is a joy to work with Vue after that Angular 2,3,4,5... mess.

Ajax autocomplete with gson on jsp

I have problem about autocomplete with ajax.
I take datas from my java class to ajax jsp file.
But i cant append it to my listing area.
index.jsp
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#keyWord2").keyup(function(){
if($(this).val().length>4){
fill_data($(this).val());
}//endif
if($(this).val().length<4){
$("#show").html("");
$("#show").css("display","none");
}//endif
});//end keyup function
});//end document ready function
function fill_data(aranan){
$.ajax({
type: "POST",
url: "ajaxSearch.jsp",
data:"name="+encodeURIComponent(aranan),
dataType: "json",
success: function(){
alert("success");
$("#show").css("display","block");
$("#show").html("");
$.each(data, function(i, item) {
$("#show").append("<div >"+item.clientNumber+"</div>");
});//end each function
}//end success function
});//end ajax
}//end fill_data
</script>
</head>
<body>
<div>
<input type="text" id="keyWord2" autocomplete="off" maxlength="50"/>
<div style=" display: none; " id="show"></div>
</div>
</body>
i call my datas from ajaxSearch.jsp and it returns me the list.But function doesnt come to success it doesnt show my element whose id is "show" and doesnt alert success.

Phonegap app works on emulator not on device

Im testing simple phonegap app for adding comment with remote server. ive tested in telerik icenium simulator and in browser and it works. But when I try to test in visual studio emulator and click the button it says "CordovaBrowser_NavigationFailed :: www/index.html?email=fgg#vv.com&comment=Gjjj". I`ve tested on device too, but there nothing happens.
Here is the code.
index.html - the main page
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;">
<title>jQuery form post</title>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/post.js"></script>
<script src="js/jquery.mobile-1.4.3.js"></script>
<script>
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
<style>
label, b {
display: block;
}
</style>
</head>
<body onload="onBodyLoad()">
//content
<div id="landmark-1" data-landmark-id="1">
<form>
<label for="email">
<b>Email</b>
<input type="email" id="email" name="email">
</label>
<label for="comment">
<b>Comment</b>
<textarea id="comment" name="comment" cols="30" rows="10"></textarea>
</label>
<input type="submit" value="Save">
</form>
</div>
</body>
</html>
post.js
$(document).bind('deviceready', function () {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.pushStateEnabled = false;
$(function () {
$('form').submit(function () {
var landmarkID = $(this).parent().attr('data-landmark-id');
var postData = $(this).serialize();
$.ajax({
type: 'POST',
data: postData + '&lid=' + landmarkID,
//change the url for your project
url: "http://bgg.comxa.com/new.php",
crossDomain: true,
success: function (data) {
console.log(data);
alert('Your comment was successfully added');
},
error: function () {
console.log(data);
alert('There was an error adding your comment');
}
});
return false;
});
});
});
As I understand this error message does not state that there is anything wrong with your index.html file, it does not seem to be able to reach it at all.
Check out this thread: Navigation in phonegap application fails when I use GET variables
There might be something about the way you try to reach your index.html file. Maybe you are going straight to "index.html" and not "www/index.html", as it states in the post answer.
Hope this helps!
After a lot of reading, i think the problem is in webkit prowsers. I`ve read that there is issues with ajax requests in webkit based browsers. I will try the code at real mobile phone device and see...

Kendo UI Mobile : Pull To refresh - list not displayed

Dynamic data is not appearing in the list. Data is fetched dynamically in jsonp format. When checked in Chrome developer tools i am able to see the response. Please find the code below. Can someone help me here ?
<!DOCTYPE html>
<html>
<head>
<title>Pull to refresh</title>
<script src="../../lib/jquery.min.js"></script>
<script src="../../lib/kendo.mobile.min.js"></script>
<link href="../../lib/styles/kendo.mobile.all.min.css" rel="stylesheet" />
<link href="../../lib/styles/kendo.common.min.css" rel="stylesheet" />
<div data-role="view" data-init="mobileListViewPullToRefresh" data-title="Pull to refresh">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
<a data-align="right" data-role="button" class="nav-button" href="#index">Index</a>
</div>
</header>
<ul id="pull-to-refresh-listview"></ul>
</div>
<script id="pull-to-refresh-template" type="text/x-kendo-template">
#= Title #
</script>
<script>
function mobileListViewPullToRefresh() {
var dataSource = new kendo.data.DataSource({
serverPaging: true,
pageSize: 1,
transport: {
read: {
url: "http://localhost/MvcMovieApp/Mobile/RestResponse", // the remove service url
dataType: "jsonp" // JSONP (JSON with padding) is required for cross-domain AJAX
},
parameterMap: function(options) {
alert(kendo.stringify(options));
return {
q: "javascript",
page: options.page,
rpp: options.pageSize
since_id: options.since_id //additional parameters sent to the remote service
};
}
},
schema: {
data: "movies" // the data which the data source will be bound to is in the "results" field
}
});
alert("Before kendoMobileListView");
$("#pull-to-refresh-listview").kendoMobileListView({
dataSource: dataSource ,
pullToRefresh: function(){ alert("dataSource"); return true },
appendOnRefresh: true,
template: $("#pull-to-refresh-template").text(),
endlessScroll: true,
pullParameters: function(item) {
return {
since_id: item.id_str,
page: 1
};
}
});
}
</script>
<script>
window.kendoMobileApplication = new kendo.mobile.Application(document.body);
</script>
</body>
</html>
JSONP which i am receiving is :
({"movies":[{"ID":1,"Title":"Movie 1","ReleaseDate":"/Date(1355250600000)/","Genre":"Comedy","Price":10},{"ID":2,"Title":"Movie 2","ReleaseDate":"/Date(1355250600000)/","Genre":"Thriller","Price":10}]})
There must be a call back function name in the returned JSONP. The output I see here doesn't have any function name. You need to make changes to your server side code.

Resources