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

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.

Related

I have writtten code to check if there is even one entry in database to give message duplicate entry

jQuery(document).ready(function(){
jQuery("#save_btn").click(function(){
kabina=jQuery("#d_id").val();
var city = $('.city option:selected').map(function(idx, elem) {
return $(elem).html();
}).get();//alert(city);
//city=jQuery("#ct_title").val();
$.ajax({
type:'POST',
url:'<?php echo $menulink;?>/checkunique',
data:{city:city,kabina:kabina},
success:function(data){
//alert(data);
if(data == 'True')
{
toastr.success("Building Created",'Attention',{"positionClass": "toast-bottom-full-width" });
$("#city_frm").submit();
}
else
{
toastr.error("Building Created",'Attention',{"positionClass": "toast-bottom-full-width" });
$("#city_frm").submit();
}
//alert(data);
}
})
})
})
Here is the ajax from which the controller check unique method is called
This is the controller
public function checkunique(){
$count=array();
if(isset($_POST['kabina'])){
//$ct_id = $_POST['ct_id'];
$kabina = $_POST['kabina'];
$city = $_POST['city'];//print_r($city);
foreach($city as $ct_title)
{//print_r($ct_title);
$ct_count=$this->mod_atyatbox_cities->city_count($ct_title,$kabina);//print_r($ct_count);die;;
$count[]=$ct_count;
}//print_r($count);die;
if(in_array(1,$count))
{
echo "False";
}
else if(in_array(0,$count))
{
echo "True";
}
}
Here is teh model where query is wrote to check for duplicate entry
function city_count($ct_title,$kabina_id)
{
$query="select ct_title from city where ct_title='$ct_title' and kabina_id=$kabina_id";
$result=$this->db->query($query)->num_rows();//echo $result;die;
return $result;
}
Here if I print the query it prints. But when I return the data it returns 0 even if there is 1.
Check all the query from the array
foreach($city as $ct_title){
$ct_count=$this->mod_atyatbox_cities->city_count($ct_title,$kabina);
$count[]=$ct_count;
$queries[]=$this->db->last_query();
}
print_r($queries);die;

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
}

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.

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;

fancybox: show partial view

I have the following js code:
function getSelectedPlace(form) {
var places = 1
$(form).find(":input").each(function () {
if ($(this).attr("name") === "Signed_Order_B64") {
$.ajax({
type: 'POST',
url: '/MyController/MyAction',
data: "id=" + places,
success: function (response) {
if (response.Result) {
ret = response.Message;
result = true;
$("input[type=hidden][name=email]").val(response.Email);
$("input[type=hidden][name=appendix]").val(response.Appendix);
} else {
// show fancybox
result = false;
}
},
error: function () {
result = false;
},
async: false
});
$(this).val(ret);
}
});
if (!result) {
$(submitButton).attr("value", btnText);
setStateFotBuyButton(false);
}
return result;
}
I have if statement in success block. I want show partial view in the fancybox in else block. How can I do this? Thanks
Not totally sure what you mean with "partial view" but you could do
} else {
$.fancybox(response,{
// fancybox options here
}); // fancybox
}
You could use the content switch which allows you to set the content of the fancybox to any html:
$.fancybox({
content: response
});

Resources