Ajax code not working only validation worked - ajax

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
}

Related

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

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.

How do I include an Ajax validator before sending

I managed to make this code to submit a form, it works fine, but I can not implement a validator does not need it, but it shows no message just does not send the form is empty.
I searched but could not quite do it. Can anyone help me?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#newsletter').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "newsletter_cadastrar.asp?f=1",
data: dados,
success: function( data )
{
$('#resultado-form-newsletter').html(data);
}
});
return false;
});
});
</script>
<input id="nomenewslbase" name="nomenewslbase" type="text">
<input id="emailnewslbase" name="emailnewslbase" type="email">
Thank you for your attention.
If you are looking for applying jquery validation rules then you can do it like:
<script type="text/javascript">
function ValidationRules() {
}
ValidationRules.prototype.initializeSaveValidators = function() {
jQuery.validator.addMethod("csProjectName",
function(value, element) {
if ($.trim($('#txtProjectName').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
} else
return true;
}, "Project Name is required");
jQuery.validator.addMethod("csDescription",
function (value, element) {
if ($.trim($('#txtDescription').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
}
else
return true;
}, "Description is required");
};
ValidationRules.prototype.enableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: true };
jQuery.validator.classRuleSettings.csDescription = { csDescription: true };
};
ValidationRules.prototype.disableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: false };
jQuery.validator.classRuleSettings.csDescription = { csDescription: false };
};
jQuery(document).ready(function () {
var validationRules = new ValidationRules();
validationRules.initializeSaveValidators();
validationRules.enableSaveValidators();
$("#btnsubmit").click(function () {
applyjQueryValidation();
return false;
});
});
function applyjQueryValidation() {
var isValid = $('#newsletter').valid();
//here you can manually check for some extra validations
if (isValid==true) {
alert("valid");
//here is you ajax call
}else{
alert("invalid");
}
}
</script>
Also, you need to include jquery.validate.js
Here is the JSfiddle working example.

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.

how to validate inputs in ajax form

I have this ajax form with name, email and message and I want to validate the inputs:
<script type="text/javascript">
$(document).ready(function(){
$form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
$("#inlocuire").fadeOut(1000, function () {
$(this).html("<img src='images/de_multumire.png'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
},'json');
return false;
});
});
I tried to introduce this function but it is not working:
$('#form_id').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter a value for name');
return false;
}
if (!email[0]) {
alert('Please enter a value for email');
return false;
}
if (!message[0]) {
alert('Please enter a value for message');
return false;
}
else {
// here to send the form
}
The form is working fine...
for those having the same problem as me: http://docs.jquery.com/Plugins/Validation

returning different javascript object from controller

my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}

Resources