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

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;

Related

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
}

Input::all() returns empty array in laravel 5

here's my ajax request. i send request to controller to remove pictures
$(document).on("click", "button[data-delete]", function(e) {
var tour_id = $("form").attr("data-tour-id");
var gallery = {};
$("input:checkbox[class = checkbox]:checked").each(function(k){
gallery[k] = $(this).attr("data-gallery-id");
});
gallery = JSON.stringify(gallery);
bootbox.confirm({
message: "გსურთ აღნიშნული სურათის წაშლა?",
callback: function(result){ }
});
$("button[data-bb-handler='confirm']").on("click",function(){
$.ajax({
headers: {'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content')},
url: "/{lang}/admin/tours/"+ tour_id +"/edit/removeGalleryPic/"+ gallery,
data : { id: tour_id, pics: gallery },
}).done(function() {
window.location.reload();
});
});
});
it works. so if request response 200(ok) page will be reloaded. but i have another form fields, and after being reloaded i want to save(flash) the values of these fields. so in controller i return input, but it returns empty array. here's my controller
public function removeGalleryPic($id, $pics)
{
$pics = json_decode($pics, true);
$tour_whole_gallery = Tour_gallery::where("tour_id", $id)->get();
if(count($tour_whole_gallery) > 0)
{
foreach($tour_whole_gallery as $gallery)
{
foreach($pics as $pic_id)
{
if($gallery->id == $pic_id)
{
unlink(public_path() . $gallery->path);
Tour_gallery::where("id", $pic_id)->delete();
}
}
}
}
return Input::all();
}
how should i return all input fields with their data? i also tried these
$request->all();
$request->flash();
redirect()->back()->withInput();
but result is the same.
you could try this:
$input = Input::all();
return response()->json($input);

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.

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.

Make a if loop according to what returns the ajax html(data)

I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}
Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});
The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}
You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}

Resources