Ajax request does not work if i dont write return false at the end - ajax

This is my validation function written on button click.
function chk_add_area()
{
var areaCountry=$('#areaCountry').val();
var areaCity=$('#areaCity').val();
var area=$('#area').val();
if(areaCountry.trim()=="")
{
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
else //if(areaCountry.trim()!="" && areaCity.trim()!="" && area.trim()!="")
{
$.ajax({
url:'ajax.php?action=duplicatearea&areaCountry='+areaCountry+'&areaCity='+areaCity+'&area='+area,
type:'get',
success:function(res)
{
if(res=="exists")
{
$('#err_div').html("Area already exists");
}
}
});
//return false;
}
/* else
{
return true;
} */
}`
if i uncomment return false,it works properly but then the form does not submit on success & i cant proceed further.
Can anyone tell me why?

You need a return false if the area already exists, otherwise drop through.
You don't need to return true; just exiting from the function works fine.
function chk_add_area() { // onsubmit handler
var areaCountry = $('#areaCountry').val().trim();
var areaCity = $('#areaCity').val().trim();
var area = $('#area').val().trim();
if ( areaCountry == "" ) {
$('#err_areaCountry').fadeIn('slow');
$('#err_areaCountry').html("Please Select Country");
$('#areaCountry').focus();
$('#err_areaCountry').fadeOut(3000);
return false;
}
if ( areaCity == "" || area == "" ) {
$('#err_div').html("Please Select City and Area");
return false;
}
$.ajax({
url: 'ajax.php?action=duplicatearea&areaCountry=' + areaCountry +
'&areaCity=' + areaCity + '&area=' + area,
type: 'get',
async: false, // EDIT: added Dec 30
success: function(res) {
if ( res == "exists" ) {
$('#err_div').html("Area already exists");
return false;
}
}
// allow form submit to proceed
}
Also, I recommend using POST instead of GET because GET is cacheable. Someone might add the same area twice.

Related

how i make a condition with ajax and asp mvc

I want to put a condition if the user want to add a second appointment he receives an alert
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
this is my code in controller :
public JsonResult SaveEvent(Event e)
{
var status = false;
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
status = true;
}
i want to make the user add one time his event and receive an alert i try but not work
I think i can help:
if(Session["appointment"] != "ok")<>
{
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
Session["appointment"] = "ok";
return JSON(new{appointment="ok"});
}
}else
{
return JSON(new {appointment="no-good");
}
and controller:
function SaveEvent(data)
{
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function(data) {
if (data.appointment == "ok")
{
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
else { your msg error here }
},
error: function() {
alert('Failed');
}
})
}
})
dont not forget Session.Clear();
as the user logs out

Bootstrap Selectpicker not refreshing

When a user clicks the edit icon the contents of a selectpicker are updated then refreshed. Then the selectpicker's value is updated, then refreshed again, but for some reason it is not updating with the selected value.
Everything works fine when I manually enter in the the same code in the console.
$('#IncWidgetId').val(864)// the value used when breaking in console
$('#IncWidgetId').selectpicker('refresh')
I have ensured that the selectpicker is updated with the new option values along with confirming the deferred is firing in the proper order.
As a double check, I also have separated the .selectpicker('refresh') to make sure it didn't try to fire before the option was selected due to async, but it is still not updating the selectpicker with the selected value.
$(document).on('click', '[id^=EditWidgetId-]', function () {
var id = $(this).attr('id').split('-')[1];
var mfg = $(this).data('mfg');
var widgetid = $(this).data('widgetid ');
var mfgSelect = $('input[name=mfg][value="' + mfg + '"]');
mfgSelect.prop('checked', true);
$.when(LoadWidgets(mfg)).then(function () {
console.log('then function');
$('#IncWidgetId').val(widgetid );
}).done(function () {
console.log('done function');
$('#IncWidgetId').selectpicker('refresh');
});
$('#modalWidgetNew').modal('show');
});
function LoadWidgets(mfg) {
var r = $.Deferred();
console.log('before ajax');
r.resolve($.ajax({
url: '/Widgets/FilterWidgetsDropdown',
type: 'GET',
cache: false,
data: { mfg: mfg },
success: function (partial) {
$('#IncWidgetDDArea').html(partial);
$('#IncWidgetId').selectpicker('refresh')
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
})).done(function () {
console.log('after ajax');
return r.promise();
});
}
What am I missing?
There was such an issue in old versions of this plugin.
Try to destroy it and initialize again. Something like this:
$('#IncWidgetId').selectpicker('destroy');
$('#IncWidgetId').selectpicker();

Ajax code not working only validation worked

Here is the JS Fiddle
My Ajax code not working i dont know how..
I used ajax below code many time but this time not working
please help me..
only this code run inside the ajax code
if(!validateee()) return false;
If validation code remove then ajax run
Ajax Code
$('#body-enquiry').submit(function(e){
e.preventDefault();
if(!validateee()) return false;
$(this).find(":submit").prop("disabled", true);
var form = $(this);
var post_url = 'enquiry-entire-mail.php';
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(data) {
alert('Submited');
}
});
});
you forgot to return true at the end of your function that is the issue.
return true;
this you need to write in you validateee function .
please find update here : https://jsfiddle.net/qref356z/6/
you updated validateee function, update below code it will work i checked it at my end
function validateee() {
var name = document.popbody.namebody.value;
var email = document.popbody.emailbody.value;
var number = document.popbody.numberbody.value.length;
var msg = document.popbody.msgbody.value.length;
alert('msg5');
if(name.trim() == "") {
alert("Please Fill Name");
document.popbody.namebody.focus();
return false;
}
alert('msg4');
if(name<3) {
alert("invalid Name");
document.popbody.namebody.focus();
return false;
}
alert('msg3');
if(email=="") {
alert("Enter Your Email");
document.popbody.emailbody.focus();
return false;
}
alert('msg2');
if(number=="") {
alert("Enter Your Number");
document.popbody.numberbody.focus();
return false;
}
alert('msg1');
if(number<9) {
alert("Your Mobile number at least 10 digit");
document.popbody.numberbody.focus();
return false;
}
alert('msg');
if(msg == "") {
alert("Enter your Message");
document.popbody.msgbody.focus();
return false;
}
return true;///you need to add here
}

after login unable to stay on current page

i am using $stateChangeStart instead of routechangestart , the problem i am facing is that after login whenever i refresh page i get redirected to home page,here is my code?
$rootScope.$on(‘$stateChangeStart’, function (event,next, toState, toParams,fromState, fromParams, options) {
if(next.name === “product.login” && $rootScope.authenticated) {
event.preventDefault();
} else if (next.name && next.data.requireLogin && !$rootScope.authenticated ) {
event.preventDefault();
$rootScope.$broadcast(“event:auth-loginRequired”, {});
}
else if (next.name && !AuthSharedService.isAuthorized(next.data.requiredRole)) {
event.preventDefault();
$rootScope.$broadcast(“event:auth-forbidden”, {});
}
}
);
$rootScope.$on(‘event:auth-loginConfirmed’, function (next,tostate,toparams, data,event)
{
console.log(‘login confirmed start for ‘ + tostate);
$rootScope.loadingAccount = false;
var nextLocation = ($rootScope.$state.current.name? $rootScope.$state.current.name : “frontProduct.productgrid”);
Session.create(tostate);
$rootScope.account = Session;
$rootScope.authenticated = true;
$state.go(nextLocation);
});
i just want to stay on current page.help me!
Hope you doing well
you have to also specify if user is not authenticated then where user redirect
if (!$rootScope.userloggedIn && !$rootScope.authenticate) {
$state.go("login");
event.preventDefault();
}
else{
$state.go("home");
}
look like this.
Hope this help you.
found answer,
$rootScope.$on('$stateChangeStart', function (event,next, toState, toParams,fromState, fromParams) {
if(next.name === "product.login" && $rootScope.authenticated) {
event.preventDefault();
} else if (next.name && next.data.requireLogin && !$rootScope.authenticated ) {
if(next.name!="product.login"&&next.name!=""){$window.localStorage.setItem('url',next.name);}
event.preventDefault();
$rootScope.$broadcast("event:auth-loginRequired", {});
}
else if (next.name && !AuthSharedService.isAuthorized(next.data.requiredRole)) {
event.preventDefault();
$rootScope.$broadcast("event:auth-forbidden", {});
}
}
);
$rootScope.$on('event:auth-loginConfirmed', function (next,tostate,toparams, data,event,$stateProvider) {
console.log('login confirmed start for ' + tostate);
$rootScope.loadingAccount = false;
$rootScope.$state.current.name : "frontProduct.productgrid");
Session.create(tostate);
$rootScope.account = Session;
$rootScope.authenticated = true;
$state.go($window.localStorage.getItem('url'));
$window.localStorage.remove('url');
});
i just want to know is this a correct way.

AJAX Form Validation to see if course already exist always return true

I want to validate my course name field if the course name inputted already exist using AJAX, but my ajax function always return the alert('Already exist') even if i inputted data that not yet in the database. Please help. Here is my code. Thanks.
View:
<script type="text/javascript">
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData= {
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/courses/check_course_name_existence",
data: postData,
success: function(msg)
{
if(msg == 0)
{
alert('Already Exist!');
return false;
}
else
{
alert('Available');
return false;
}
return false;
}
});
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
}
</script>
Controller:
function check_course_name_existence()
{
$course_name = $this->input->post('course_name');
$result = $this->course_booking_model->check_course_name_exist($course_name);
if ($result)
{
return true;
}
else
{
return false;
}
}
Model:
function check_course_name_exist($course_name)
{
$this->db->where("course_name",$course_name);
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
You could use console.log() function from firebug. This way you will know exactly what the ajax returns. Example:
success: function(msg) {
console.log(msg);
}
This way you also know the type of the result variable.
jQuery, and Javascript generally, does not have access to the Boolean values that the PHP functions are returning. So either they return TRUE or FALSE does not make any difference for the JS part of your code.
You should try to echo something in your controller and then make your Javascript comparison based on that value.

Resources