autocomplete function not working for mobile view - laravel

Hello I am creating searching task in my project it works fine for destop view but when i open my website in mobile and press key then keypad is open and close within second what is problem in my code. What is mistake? why code is not working in mobile view?
//html
<form class="ps-search--header" action="#" method="post">
{{ csrf_field()}}
<input class="form-control" type="text" placeholder="Search Product…" id="product_name">
<button><i class="ps-icon-search"></i></button>
<div id="product_list"></div>
</form>
//controller
public function fetch(Request $request)
{
if($request->get('query'))
{
$query = $request->get('query');
$data = DB::table('products')
->where('product_name', 'LIKE', "%{$query}%")
->get();
$output = '<ul class="dropdown-menu" style=" display:block; ;width:100%">';
foreach($data as $row)
{
$name=[];
$name=explode(" ",$row->product_name);
$output .= '
<li>'.$row->product_name.'</li>
';
}
$output .= '</ul>';
echo $output;
}
}
//autocomplete
$('#product_name').keyup(function(){
var query = $(this).val();
if(query != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"/autocomplete",
method:"get",
data:{query:query, _token:_token},
success:function(data){
$('#product_name').fadeIn();
$('#product_list').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#product_name').val($(this).text());
$('#product_list').fadeOut();
});

This kind of keyup wold not work sometimes with mobile which work great on desktop
You can use this Keyup on Your autocomplete function its work on both check the code bellow
$('#product_name').on('keyup input', function(e){
if(e.keyCode == 13) {
$("input").blur();
}
var query = $(this).val();
if(query != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"/autocomplete",
method:"get",
data:{query:query, _token:_token},
success:function(data){
$('#product_name').fadeIn();
$('#product_list').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#product_name').val($(this).text());
$('#product_list').fadeOut();
});

Related

Problem using Laravel when I add a record

Great to know you!
I have a problem when I use Laravel to make book bus tickets online system :((. I import *.sql by phpMyadmin so I don't create file migrate.
This is lichtrinh table
Everything is well (1st record and 2nd record my application working well) but until I add 3rd record to table, ajax() alert ('Not submit') Althought I just add new record
My file js
$(document).ready(function () {
$('#btn-submit').click(function (e) {
e.preventDefault();
$username = $('#username').val();
$pass = $('#pass').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "/login",
type: "POST",
data: {
username: $username,
pass: $pass
},
success: function (data) {
if (data == '') {
window.location = "/ve/banve"
} else {
$('.toast-container').empty();
$('.toast-container').append(data);
$('.toast').each(function (indexInArray,
valueOfElement) {
var toast2 = new bootstrap.Toast($(this));
toast2.show();
});
}
},
error: function () {
alert("Not submit")
},
});
});
});
My controller
public function findLichTrinh(Request $request)
{
$lichtrinhs = LichTrinh::where('id_tuyen', $request->id_tuyen)->where('ngaydi', $request->ngaydi)->get();
$output = "";
if (!empty($lichtrinhs)) {
foreach ($lichtrinhs as $lichtrinh) {
$output .= '<div class="main-item-roundbus m-2 able-cursor">
<div class="main-item-title d-inline-flex justify-content-around align-items-center">
<span class="text-white">' . $lichtrinh->giodi . '</span>
<span class="text-white border border-3 p-1" style="border-radius: 5px;">' . $lichtrinh->xes->bienso . '</span>
</div>
<div class="px-2">
<span style="font-size: 17px;" class="fw-bold text-danger text-center">' . $lichtrinh->tuyens->name_tuyen . '</span>
<br>
<span style="font-size: 17px;">Ghế trống: 10</span><br>
<span style="font-size: 17px;">Gía: 100 000 VNĐ</span><br>
</div>
</div>';
}
} else {
$output = '<h1>Not Found</h1>';
}
return $output;
}
My route
Route::get('/ve/banve/lichtrinh', 'App\Http\Controllers\VeController#findLichTrinh');
Thank you very much! Please help me. I'm so sorry, I know my English is not well

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

Search results to show in blade using ajax and laravel

I have a search place for costumers to search the product which will be displayed in blade. I am using ajax and laravel. Here is my code as much as I wrote. The query works well and when I print $filter I can see the results.
$('.gotosearch').on('click' , function() {
var search = $(this).val()
var inpvalue = $('.form-control').val()
$.ajax({
url:'/searchproducts',
type:'post',
data: {
inpvalue,
"_token" : token
},
success:function(r) {
console.log(r)
}
})
})
Route::post('/searchproducts' , 'ProductController#searchproducts');
function searchproducts(Request $search) {
$filter = ProductModel::where('Product_Name','LIKE', $search->inpvalue.'%')->get();
}
You can use response()->json in you controller
As per Laravel documentation
The json method will automatically set the Content-Type header to
application/json, as well as convert the given array to JSON using the
json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
Try this:
return response()->json($filters->toArray());
https://laravel.com/docs/5.8/responses#json-responses
try this:
// search text
<div class="form-group">
<input type="text" id="search" name="search" class="form-control" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Search" value="{{ old('accountNo') }}" style="font-size:20px;font-weight:bold;" required>
</div
// search result
<div id="getResult" class="panel panel-default" style="width:400px; height: 150px; overflow-y:auto; position:absolute; left:50px; top:180px; z-index:1; display:none;background-color:white">
<div id="getList"></div>
</div>
//ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').keyup(function(){
var search = $('#search').val();
if(search==""){
$('#getResult').css('display', 'none').hide();
}
else{
var getQueries = "";
$.get("{{ url('/') }}" + '/search/' + search,
{search:search},
function(data){
if(data){
$('#getResult').css('display', 'block');
}else{
$('#getResult').css('display', 'none')
}
if(search == ''){
$('#getResult').css('display', 'none').hide();
}else{
$.each(data, function (index, value){
var id=value.ID;
getQueries += '<ul style="margin-top:3px; list-style-type:none;">';
getQueries += '<a href={{ url("add-contribution-amount")}}' +'/'+ value.id + '>' + value.fullname +' | '+value.accountno + '</a>';
getQueries += '</ul>';
});
$('#getList').html(getQueries );
}
})
}
});
</script>
//controller
public function CustomerSearch($getSearch){
$search = $getSearch;
$members = DB::table('tblcustomers')
->where('accountno', 'like', "%$search%")
->select('id','branchID', 'fullname', 'savingstype', 'accountno')
->orderby('id','asc')
->get();
return $members;
}
//route
Route::get('/search/{searchQuerys?}', 'ContributionController#CustomerSearch');

I can't update status by use the checked box

Please help i can't update the status by use the checked box.
When i selected the check box and select delete button, status will change to 'deleted' but now i can't update the data.
This is my view
<a href="javascript:;" id="delete" class="myButton" >Delete</a>
<div>
<input type="checkbox" class="cb_invoice" id="<?php echo $r->INVOICENUMBER;?>" value="<?php echo $r->INVOICENUMBER;?>">
</div>
This my script
<script>
$('#delete').click(function() {
var _url = "<?php echo site_url('commission/delete_invoices');?>";
var d_obj = $(".cb_invoice");
var d_val = [];
for (var i = 0; i < d_obj.length; i++){
if(d_obj[i].checked){
d_val.push(d_obj[i].value);
}
}
$.ajax({
url: _url,
data: {data: d_val},
type: 'post',
success: function(data) {
//console.log(data);
location.reload();
}
});
});
</script>
This my controller
function delete_invoices(){
$invoice = $this->input->post('data');
foreach ($invoice as $invoice) {
$this->m_commission->delete_invoice($invoice);
}
}
This is my model
function delete_invoice($invoice){
$this->db->update('salesinvoiceheader');
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
}
Change the order of update as follows in your modal:-
function delete_invoice($invoice){
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
$this->db->update('salesinvoiceheader');
}

Form submission using AJAX and handling response in Wordpress Website

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>
Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}
You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box
First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

Resources