Semantic UI custom form validation with Ajax - ajax

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
}
});

Related

Getting Error in codeigniter ajax dropdown changing

Getting Error in codeigniter ajax dropdown changing
[![enter image description here][1]][1]
function fun1(sid) {
//alert(sid);
var obj;
if (window.XMLHttpRequest) {
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP")
}
obj.open("post", "https://99shopin.com/register/getcity?val=" + sid, true);
obj.send();
obj.onreadystatechange = function() {
if (obj.readyState == 4) {
document.getElementById('div1').innerHTML = obj.responseText;
} else {
document.getElementById('div1').innerHTML = "";
}
}
}
Try this, and check Is there still an error?
function fun1(sid){
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('register/getcity'); ?>",
data: ({val: sid}),
//dataType: "json",
success: function (data) {
document.getElementById('div1').innerHTML = data.responseText;
}
});
}

Cake PHP div refresh server crashed

I'm using cake php
For 8 times I have used div refresh pattern from the server but after few minutes my server crashed and I have to ask the server provider to reopen the server.
What would be the best way to proceed if I want to use the database through div refresh?
function check()
{
$.ajax({
type : 'POST',
url : '<?php echo $this->webroot;?>'+'Bookings/rand_f',
dataType : 'html',
data: {},
cache : false,
success:function(result){
$('#ht').html(result);
$("#session_value").val(result);
}});
}
setInterval(check, 1000);
function check_count()
{
var a=$("#session_value").val();
$.ajax({
type : 'POST',
url : '<?php echo $this->webroot;?>'+'Bookings/check_count/'+a,
dataType : 'html',
data: {},
cache : false,
success:function(result){
if(result=='change'){
$('#res').val(result);
listings_live1();
}else{
$('#res').val('no_change');
}
}});
}
setInterval(check_count, 1000);
function listings_live1()
{
var a=$("#session_value").val();
$.ajax({
type : 'POST',
url : '<?php echo $this->webroot;?>'+'Bookings/listingsbookingcheck/'+a,
dataType : 'html',
data: {},
cache : false,
success:function(result){
var x= $('#live_listing').html(result);
if(x){
return 1;
}
}});
}
function check_count_all()
{
var x=$("#last_count_all").val();
$.ajax({
type : 'POST',
url : '<?php echo $this->webroot;?>'+'Bookings/check_count_all',
dataType : 'html',
data: {},
cache : false,
success:function(result){
$("#count_all").val(result);
if(result!=x){
listings_liveall();
$("#last_count_all").val(result);
$("#st").val('change');
}
else{
$("#st").val('nochange');
}
}});
}
setInterval(check_count_all, 1000);
function listings_liveall()
{
$.ajax({
type : 'POST',
url : '<?php echo $this->webroot;?>'+'Bookings/listingall',
dataType : 'html',
data: {},
cache : false,
success:function(result){
$('#listings_liveall').html(result);
}});
}
function showaction(str,id){
$("#boking_status_call_cancel").show();
$("#alertshow").html('Are you sure you want to '+str+' this Booking?');
if(str!='accept'){
$("#reject_reason").show();
}else{
$("#reject_reason").hide();
}
$("#role_call").val(str+','+id);
}
function update_mobile_booking(){
var strcall=$("#role_call").val();
$.ajax({
type : 'POST',
url : '<?php echo $this->webroot;?>'+'Bookings/update_booking_mobile/'+strcall,
dataType : 'html',
data: {},
cache : false,
success:function(result){
var x=listings_live1();
if(x==1){
listings_liveall();
}
}});
}
/*settimeout page load mobile booking*/
var myFunc = function() {
listings_live1();
listings_liveall();
}
window.onload = function() {
setTimeout(myFunc, 1000);
}
/*
function check_counter_upper(){
c1=$("#session_value").val();
c2=$("#count_chk_cl").val();
if(c1!=c2 && c2!='undefined'){
listings_live1();
$("#st1").val('force_change');
}else{
$("#st1").val('no_force_change');
}
}
setInterval(check_counter_upper, 4000);*/

check username already existed with semantic-ui validation and semantic-ui api?

$.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)

wrong ajax callback invoked using cordova

In my jqm app I make a POST using jQuery $.ajax sending and receiving json data. Everything is fine in the browser and on iPhone; on Android I noticed that when this server response is like this:
{ "code" : 500,
"errorMsg" : "bla bla bla",
"errors" : null,
"status" : "INTERNAL_SERVER_ERROR",
"success" : false
}
the ajax invokes the "error" callback and not the "success". This happens only on android and only if I include corova-2.0.0. js on the project. Any help?
I'm using cordova-2.0.0 with jqm 1.3.1 and jQuery 1.9.1
Here's my code:
var ajax = $.ajax({
type: "post",
url: url,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
timeout: 30000
});
var success = function (d) {
if(d.success==true && obj.success)
obj.success(d.data);
else
{
var msg = parseErrors(d);
console.log(msg);
//open page passing results
obj.msgBus.fire("RequestResult", {
callback: function(){ obj.msgBus.fire("Welcome");},
success: false,
text: msg
});
}
};
var error = function (xhr, status, e) {
console.log('error ajax url:[' + url + '] status:[' + status + '] error:[' + e + ']');
if (obj.error) {
if ((typeof e == 'string'))
obj.error({
statusText: e,
code: xhr.statusCode,
text: xhr.responseText
});
else {
e = $.extend(e, {
statusText: status
});
obj.error(e);
}
}
};
var complete = function () {
if (obj.complete) {
obj.complete();
}
};
var parseErrors = function(d){
console.log( d);
if(d.errors==null){
return d.errorMsg;
}
else
{
var res="";
for (var i=0;i< d.errors.length;i++){
res+= "{0}: {1} <br/>".format( d.errors[i].field, d.errors[i].errorMsg);
}
return res;
}
};
ajax.success(success).error(error).complete(complete);
where data is an object like this:
{
"date" : 1371679200000,
"idBeach" : "1",
"idStuff" : 3,
"idUser" : "8",
"numStuff" : 1
}
Try this, it works for me
$.ajax({
async: false,
type: "POST",
url: "Your_URL",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, object) {
alert(obj.Data);
});
},
error: function () {
alert("There was an error loading the feed");
}
});

How to use ajaxStart if $.ajax method is defined in a class?

I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.

Resources