$.fn.form.settings.rules["checkUsername"] = function(value) {
var url = "/Index/checkUsername";
var res = true;
$.ajax({
async : false,
url : url,
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data){
if(data['code']==1){
res = false;
}else {
res = true;
}
console.log(res);
return res;
}
});
};
var validation = {
username : {
identifier : 'username',
rules : [
{ type : 'empty', prompt : 'Please enter your email' },
{ type : 'checkUsername', prompt : 'Username already existed' }
]
}
};
It did not work, but the console log is right.
I am using similar kind of validation but not doing an ajax call.
Curious: Can you put a logging statement just after the ajax call and see if the validation rule is returning before the ajax call?
I would also consider putting the return statement below the ajax call (still inside of the validation function)
Related
I am using a event handler that checks if the product id or name already exist. But my problem is when I am using JSON.stringify() my C# controller does not receive the data from the ajax call,.
// check if Product name already exist
$('#productName').bind('keyup blur', function () {
// check if input is empty
if ($(this).val().length > 0) {
var data = JSON.stringify({
value: $(this).val(),
fieldName: 'productName'
});
$.ajax({
type: "post",
url: '/Product/ValidateProductDetailsExist',
contenttype: "application/json; charset=utf-8",
datatype: "json",
data: data,
context: this,
success: function (result) {
if (result === true) {
// append error message
// check if error message already exist
if ($('#errorprodcutName').length === 0) {
var errormessage = '<div class="col-md-offset-2"><span id = "errorprodcutName" class="validation-error-message">Product name already exist</span></div >';
$('.form-group:nth-child(2)').append(errormessage);
}
$(this).focus();
//disables the save button
$('#btnSaveProduct').prop('disabled', true);
}
else {
// check if error message already exist
if ($('#errorprodcutName').length > 0) {
$('#errorprodcutName').remove();
}
//enables the save button
$('#btnSaveProduct').prop('disabled', false);
}
},
error: function () {
alert("unable to request from server");
}
});
}
});
When I use debugger to check the value, it is null. I don't see any errors that displays in the console as well. Can anyone please explain to me why it is not working.
public JsonResult ValidateProductDetailsExist(string value, string fieldName)
{
using (POSEntities3 db = new POSEntities3())
{
bool isExist = false;
switch (fieldName)
{
case "productId":
var dataItemProductId = db.Products.Where(product => product.product_id == value).SingleOrDefault();
isExist = (dataItemProductId != null);
break;
case "productName":
var dataItemProductName = db.Products.Where(product => product.name == value).SingleOrDefault();
isExist = (dataItemProductName != null);
break;
}
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}
I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?
I am trying to implement custom form validation rules for my username field, which should check the database for duplicated or not.
After Searching on the internet, I had write out some code, and it successful getting the response "true / false" from my server. But the fields in the form doesn't update as it should. Below was my javascript code.
$.fn.form.settings.rules.checkUsername = function(value) {
var res = true;
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
console.log(data.result);
return false;
} else {
console.log(data.result);
return true;
}
}
});
};
$('.ui.form').form({
username: {
identifier : 'username',
rules: [{
type : 'checkUsername',
prompt : 'Username Already Exists'
}]
}
// some other rules
}, {
inline : true,
on : 'blur',
onSuccess : function(){
//post to controller
}
});
The console.log showing me the correct result as I want, but I keep getting "Username Is Exist" as show at the picture
Semantic UI form Validation result
May I know where are the place I doing it wrong ?
Somehow, Added Async at the ajax solve the problem.
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
async: false,
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
console.log(data.result);
res = false;
}
}
});
Put result in the res variable and return the res variable after the ajax call !
Work for me :
$.fn.form.settings.rules.checkemail = function(value) {
var res = true;
$.ajax({
async : false,
url: '../php/email_exist.php',
type : "POST",
async: false,
data : {
email : value
},
success: function(data) {
console.log(data);
if (data == "0") {
console.log("OK");
res = true;
} else {
console.log("KO");
res = false;
}
}
});
return res;
};
$.fn.form.settings.rules.checkUsername = function(value) {
var res = true;
$.ajax({
async : false,
url: '<?= Yii::app()->createAbsoluteUrl('home/doCheckUsername') ?>',
type : "POST",
data : {
username : value
},
dataType: "json",
success: function(data) {
if (data.result == true) {
//console.log(data.result);
//return false;
**value = 0;**
} else {
//console.log(data.result);
//return true;
**value = 1;**
}
}
});
**return (value == 1 )? true : false;**
};
$('.ui.form').form({
username: {
identifier : 'username',
rules: [{
type : '**checkUsername[value]**',
prompt : 'Username Already Exists'
}]
}
// some other rules
}, {
inline : true,
on : 'blur',
onSuccess : function(){
//post to controller
}
});
Following Code is not working for my windows Application.
It Always returns "system.collections.generic.dictionary 2 system.string system.object" Error.
I tried replacing json with text and it returns successful but invalid data.
$.ajax({
dataType: "json",
url :$(this).attr('action'),
type : 'POST',
data : {
'action' : $('#action').val(),
'user' : $.trim($('#user_id').val()),
'password' : $.trim($('#password').val())
},
success : function(response)
{
if(response=="Error")
{
isUserLogged=false;
$.mobile.hidePageLoadingMsg();
alert("Authentication Failed");
}
else
{
isUserLogged=true;
machinenames = response;
server_names =[];
var temp1 = [],i=0,head='',id='';
for(var index in machinenames)
{
head = machinenames[index];
id = index;
temp1.push({heading:head,machid:id});
}
if(temp1.length>0)
{
server_names.push({'server_names':temp1});
}
$.mobile.changePage('#machines_page', {transition:'slide'});
}
},
error : function(error)
{
isUserLogged=false;
$.mobile.hidePageLoadingMsg();
alert(Error);
//alert("Error: Authentication Failed");
}
});
I am getting HTTP error 405 verb not allowed. As sometimes code works and sometimes throws http 405 error, I need to understand whether this is programming problem or server configuration problem. I am using ajax with jquery. I have gone through all related posts here and tried all recommended options related with the code. Please help.
my javascript code is as follows
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#name_error").show();
$("input#email").focus();
return false;
}
var textquery = $("textarea#textquery").val();
if (textquery == "") {
$("label#name_error").show();
$("textarea#textquery").focus();
return false;
}
var dataString = name + email + textquery;
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "samplemail.aspx",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form <br> Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Problem solved
the way Of passing parameter was wrong i.e.data : datastring .
The correct way is data : { name : name, email: email, textquery: textquery}