jquery auto complete does not work on every field - php

I use codeigniter. And I have three field with the class .eghamat. I don't know why autocomplete doesn't work in the two first fields (INSERT VALUE HERE 1, INSERT VALUE HERE 2) but works in the third(INSERT VALUE HERE 3).
The problem might come from one of the following:
The php code
the $.each loop
the ajax call
Does someone see what's wrong?
html:
<div class="bg_units bu0">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 1">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu1">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 2">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu2">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 3">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
php:
function auto_complete() {
$hotel_search = $this ->input-> post('hotel_auto');
$query = $this->db->query("SELECT * FROM hotel_submits WHERE name LIKE '%$hotel_search%' ORDER BY name asc");
if($query->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query->result() as $row)
{
$units = json_decode($row->units);
$data[] = array('name' => $row->name, 'units' =>$units );
}
}
echo json_encode($data);
}
jQuery:
$('.auto_complete_eghamat').live('keyup',function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(dataObj);
var id_name = $(bu_num+' .list_autobox_hotel').attr('id');
$(bu_num+' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num+' .search_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p id="' + value.name + '">' + value.name + '</p>').appendTo(bu_num+' .list_autobox_hotel');
});
$('body').click(function () {
$(".list_autobox_hotel p").hide().remove();
$('.auto_complete').val('');
$('.list_autobox_hotel').show().html('');
$('.list_autobox_hotel').css('display', 'none');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});

could you please rename id="tour" and id="hotel" cz html cannot have same ids multiple times
id="tour"
and also
id="hotel"
appears 3 times in the code so please look into it.

could you please try it out. and let me know.your admin.js should be like this
$(document).ready(function () {
$('.list_autobox_hotel p').click(function() {
$(this).parent().parent().find('.eghamat').val($(this).text());
});
$(document).click(function() {
if($('.list_autobox_hotel').is(':visible')){
$('.list_autobox_hotel').hide();
}
return true;
});
////////////////////////////////////////////////////////////////
$('#loadingDiv').hide() // hide it initially
.ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});
///////auto_complete///////////////////////////////////////////////
$('.eghamat').live('keyup', function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
//alert(dataObj);
$.ajax({
type: "POST",
dataType: 'json',
//url: 'binboy.gigfa.com/admin/…',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(bu_num);
var id_name = $(bu_num + ' .list_autobox_hotel').attr('id');
$(bu_num + ' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num + ' .list_autobox_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p >' + value.name + '</p>').appendTo(bu_num + ' .list_autobox_hotel');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});

Here is a simple code
$('.eghamat').click(function(){
var id =$(this).attr('id');
//Here you have the id select with it and put your code in it
});

Related

How to automatically send a discount coupon when it exists in the url?

I have created a discount coupon system, everything is working perfectly.
From the following form I send the information by ajax
<div class="form-group relative">
<div class="response">
<div class="success"></div>
<div class="warning"></div>
</div>
<form id="coupon" class="mt-2em" method="post" autocomplete="off" enctype="multipart/form-data">
<div class="form-group flex justify-between">
<div class="promo">
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon">
</div>
<div class="btn-promo">
<input id="submit_coupon" type="submit" name="ajaxData" value="Apply" formnovalidate>
</div>
</div>
</form>
</div>
And, this is my ajax code
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
})
});
});
How do I mention this all right, but with the same ajax code, how can I send the coupon code automatically when the coupon is being shared by the URL?
That is, if I have the following in the url: example.com/?codecoupon=EADEAA So I want to automatically send that information to Ajax only if there are those parameters in the URL.
In your HTML:
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon" value="<?= isset($_GET['codecoupon']) ? $_GET['codecoupon'] : '' ?>">
(In order to avoid XSS injections you want to wrap it with htmlspecialchars)
In your JS you should make the sending code a function, then call it:
On submit
On load: only if the input is not empty.
The script will look something like this:
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
sendCoupon(frm);
});
if ($("input[name='couponCode']").val() !== "") {
sendCoupon(frm);
}
function sendCoupon(frm) {
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
});
}
});

JQuery: Cannot Access php file using Relative Path

Really struggling to get a relative path to work for an Ajax request.
From like.js I'm trying to get to likeunlike.php
Error message:
jquery-3.3.1.js:9600 POST http://localhost:8000/serverside/likeunlike.php 404 (Not Found)
File structure:
JQuery:
$(document).ready(function(){
// like and unlike click
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
// AJAX Request
$.ajax({
url: '../serverside/likeunlike.php',
type: 'post',
data: {postid:postid,userid:userid},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
});
});
});
Have provided the index file as requested by one of the answers. Hope it helps.
Index.php:
<?php
include "detail/config.php";
?>
<html>
<head>
<title>Talk</title>
<link href="style/style.css" type="text/css" rel="stylesheet" />
<script src="jquery/jquery-3.3.1.js" type="text/javascript"></script>
<script src="search/script/like.js" type="text/javascript"></script>
<script src="search/check/check.js" type="text/javascript"></script>
</head>
<script>
$(function() {
$('form').on("submit", function(e) {
e.preventDefault();
$('#error').text(""); // reset
var name = $.trim($("#search").val());
if (name.match(/[^a-zA-Z0-9 ]/g)) {
$('#error').text('Please enter letters and spaces only');
return false;
}
if (name === '') {
$('#error').text('Please enter some text');
return false;
}
if (name.length > 0 && name.length < 3) {
$('#error').text('Please enter more letters');
return false;
}
$.ajax({
url: 'search/search.php',
method: 'POST',
data: {
msg: name
},
dataType: 'json',
success: function(response) {
$(".content").html("")
$(".total").html("")
if(response){
var total = response.length;
$('.total') .append(total + " Results");
}
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
$('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
});
});
}
});
});
});
</script>
<body>
<form action="index.php" method="post" id="myForm" autocomplete="on"><pre>
<input name="msg" id="search" type="text" autofocus value= "<?php if(isset($_POST['msg'])) {
echo htmlentities ($_POST['msg']); }?>"></input> <span id="error"></span>
<input type="submit" style="border:0; padding:0; font-size:0">
</pre></form>
<div class="total">
</div>
<div class="content">
</div>
</body>
</html>
jquery / js has no information about his location.
this should be work.
var base_url = window.location.origin;
// like and unlike click
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
// AJAX Request
$.ajax({
url: base_url + '/search/serverside/likeunlike.php',
type: 'post',
data: {postid:postid,userid:userid},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
});
});
});
I have resolved the situation by:
Making my directory structure simpler as well as the file names. It was over-engineered. I have my root folder now and then just one level below that for folders.
The Ajax url path, which I was struggling with was amended to 'serverside/like.php', which picked up the php file but nothing happened.
Reviewing the like.php code I had an include("../con/config.php") without a ';'. I added this and it's now working fine.
Thank you for everyone's help. Much appreciated as always.
New folder structure:

Codeigniter form validation in ajax

How can i go back to the view page and modal with the validation errors if the validation runs false ..
I want to show validation errors in the modal ..
Im new to jquery ajax ..
Is there needed to add in my jquery .. or what way can i do it..
Controller
public function update(){
$this->form_validation->set_rules('lname', 'Family Name', 'required');
if ($this->form_validation->run() == FALSE) {
}
else {
$this->home_model->update();
redirect(base_url());
}
}
Jquery
$(document).on('click', '#update', function() {
console.log($(this).attr('data-registerid'));
$.ajax({
url: "<?php echo base_url('home/get_data')?>",
type: "POST",
dataType: "JSON",
data: {
"id": $(this).attr('data-registerid')
},
success: function(data) {
console.log(data);
$('#no').val(data.rec['no']);
$('#lname_edit').val(data.rec['lname']);
$('#fname_edit').val(data.rec['fname']);
$('#mi_edit').val(data.rec['mi']);
$('#bdate_edit').val(data.rec['bdate']);
$('#module_edit').val(data.rec['module']);
$('.updatemodal').modal({
backdrop: 'static',
keyboard: false
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
To pass form validation status to client, use the below code in your controller. The code responds with a json-formatted, error, and notice text.
if ($this->form_validation->run() == FALSE) {
$json_response['form_errors'] = $this->form_validation->error_array();
exit(json_encode($json_response));
}
Client side, in your jquery ajax success handler, you can use the below code so the status response emitted server side is displayed to the client.
if (data.form_errors != undefined) {
var errors = '';
$.each(data.form_errors, function(i, val) {
errors = errors + "\n" + val;
});
if (errors != "") alert(errors);
}
else {
alert('no error(s) in form... submit form..');
}
Alternative to the above js code:
For updating each form elements' status when they change, use the below code. Place it outside your form submit handler.
function update_form_validation() {
$("input,select,textarea").on("change paste keyup", function() {
if ($(this).is(':checkbox') == true) {
$(this).siblings("label:last").next(".text-danger").remove();
} else if ($(this).is(':radio') == true) {
$(this).siblings('input[type="radio"][name="' + $(this).attr('name') + '"]:last').next(".text-danger").remove();
$(this).next(".text-danger").remove();
} else {
$(this).next(".text-danger").remove();
}
});
}
update_form_validation();
For displaying general notice and displaying each errors and notices right after their respective form element,
use the below code. In your form submit handler, place the code inside your ajax success function.
if (data.form_errors != undefined) {
$.each(data.form_errors, function(i, val) {
if ($('input[name="' + i + '"]').is(':hidden') == false) {
if ($('input[name="' + i + '"]').is(':radio') == true) {
$('input[name="' + i + '"]:last').after('<div class="text-danger">' + val + '</div>');
} else if ($('input[name="' + i + '"]').is(':checkbox') == true) {
$('input[name="' + i + '"]').siblings("label:last").after('<div class="text-danger">' + val + '</div>');
} else {
$('input[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
$('select[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
$('textarea[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
}
}
});
} else {
alert('no errors in form... submit form..');
}
You can use CodeIgniter form validations function :
$errors = array();
if ($this->form_validation->run() == FALSE) {
$errors['validation_error'] = validation_errors();
echo json_encode($errors);
exit();
}
Now in jquery:
$(document).on('click', '#update', function() {
console.log($(this).attr('data-registerid'));
$.ajax({
url: "<?php echo base_url('home/get_data')?>",
type: "POST",
dataType: "JSON",
data: {
"id": $(this).attr('data-registerid')
},
success: function(data) {
var myObj = JSON.parse(data);
$('#error_div').html(myObj.validation_error);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
View
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title">Login Form</h5>
</div>
<div class="modal-body">
<div id="modelError"></div>
<form method="post" action="javascript:void(0)">
<div class="input-group">
<input type="text" name="name" id="name" placeholder="First Name">
</div>
<div class="input-group">
<input type="text" name="last_name" id="last_name" placeholder="Last Name">
</div>
<input type="submit" id="my_form" name="Save">
</form>
</div>
</div>
</div>
</div>
Script
<script>
$('#my_form').click(function(){
$.ajax({
url: "<?php echo base_url('controller/function')?>",
type: "POST",
data: {
'name': $('#name').val(),
'last_name': $('#last_name').val(),
},
success: function(data) {
var myObj = JSON.parse(data);
var msg = '<div class="alert alert-danger alert-dismissable">'+myObj.error+'</div>';
$('#modelError').html(msg);
},
error: function() {
alert('Error get data from ajax');
}
});
});
</script>
Controller
public function insert()
{
if(isset($this->input->post())){
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('last_name','Last Name','required');
if ($this->form_validation->run() == FALSE)
{
$this->msg['error'] = validation_errors();
echo json_encode($this->msg);
}else{
$this->your_model->insert($this->input->post());
redirect(base_url());
}
}else{
$this->load->view('view-page');
}
}

Dependent dropdown menu using ajax not refreshing but console is showing data

I am using a MVC structure and here is the JQuery:
<script type="text/javascript">
$('select[name="provider_id"]').change(function() {
var provider_id = $(this).val();
if (provider_id) {
$.ajax({
url: url + '/ProductsAjax/GetOutletByProvider',
type: 'POST',
dataType: 'json',
data: {
provider_id: provider_id
},
})
.done(function(data) {
$.each(data, function(index, item) {
var outlets = "<option value='" + item.id + "'>" + item.outlet_name + "</option>";
$('select[name="outlet"]').append(outlets);
console.log(item.id + ' ' + item.outlet_name);
})
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
} else {
$('select[name="outlet"]').empty();
}
});
</script>
It is outputting the correct data in console but the dropdown menu itself does not show the data at all. Nothing happens.
Here are the select menus:
<div class="form-group m-form__group">
<label for="example_input_full_name">
Select Service Provider
</label>
<select class="form-control m-bootstrap-select m_selectpicker" name="provider_id">
<option value="">Select Service Provider</option>
<?php foreach($data['sproviders'] as $service_provider): ?>
<option value="<?php echo $service_provider->service_provider_id; ?>"><?php echo $service_provider->sp_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group m-form__group">
<label for="example_input_full_name">
Select Outlet
</label>
<select class="form-control m-bootstrap-select m_selectpicker" name="outlet" id="outlet">
</select>
</div>
Since the correct data is displaying in console, I can't figure out why it isn't pulling through into the second select menu.
Console data:
108 Branch One
109 Branch Two
110 Branch Three
<script type="text/javascript">
$('select[name="provider_id"]').change(function() {
var provider_id = $(this).val();
if (provider_id) {
$.ajax({
url: url + '/ProductsAjax/GetOutletByProvider',
type: 'POST',
dataType: 'json',
data: {
provider_id: provider_id
},
})
.done(function(data) {
var outlets="";
$.each(data, function(index, item) {
outlets += "<option value='" + item.id + "'>" + item.outlet_name + "</option>"; // concat all options
console.log(item.id + ' ' + item.outlet_name);
})
$('select[name="outlet"]').html(outlets); // add all options
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
} else {
$('select[name="outlet"]').empty();
}
});
</script>

I can not click again remove or add button

I want to create an Add and Remove from ordered lists button for my site.
But I can not click again when I click add button or remove button.
<script>
$(document).ready(function () {
$('.order-lists div #add').click(function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
$('.order-lists div #remove').click(function(e) {
$('.order-lists div').removeClass('remove');
var $parent = $(this).parent();
if (!$parent.hasClass('remove')) {
$parent.addClass('remove');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.removeCookie(ids, null);
$.removeCookie(name, null);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).removeClass('remove');
$("#" + ids).append('<a class="btn btn-danger" id="add" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Add Order List </a>');
});
}
e.preventDefault();
});
});
</script>
use on function for dynamically added elements.
$(document).ready(function () {
$('.order-lists').on('click', '#add' , function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
});
same for remove.

Categories