I saw a tutorial on AJAX Autocomplete it looks ok but the problem is it also display all the data not the one I am searching for.
sorry I am new to ajax can you help me fixing this?
from my Controller
public function search(Request $request){
// check if ajax request is coming or not
if($request->ajax()) {
// select country name from database
$data = Vendor::where('vendor_id', 'LIKE', '%'.$request->vendor_id.'%')
->get();
// declare an empty array for output
$output = '';
// if searched countries count is larager than zero
if (count($data)>0) {
// concatenate output to the array
$output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
// loop through the result array
foreach ($data as $row){
// concatenate output to the array
$output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
}
// end of output
$output .= '</ul>';
}
else {
// if there's no matching results according to the input
$output .= '<li class="list-group-item">'.'No results'.'</li>';
}
// return output result array
return $output;
}
}
My Blade
<div class="row">
<div class="col-lg-12"></div>
<div class="col-lg-6">
<div class="form-group">
<input type="text" name="vendor_id" id="vendor_id" data-type="vendor_id" placeholder="Enter vendor ID" class="form-control autocomplete_txt">
{{-- <input class="typeahead form-control" type="text"> --}}
</div>
<div id="vendor_list"></div>
</div>
<div class="col-lg-6">
<div class="form-group">
<input type="text" name="vendor_name" id="vendor_name" placeholder="Vendor Name" class="form-control" readonly="true">
</div>
</div>
<div class="col-lg-12"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script type="text/javascript">
// jQuery wait till the page is fullt loaded
$(document).ready(function () {
// keyup function looks at the keys typed on the search box
$('#vendor_id').on('keyup',function() {
// the text typed in the input field is assigned to a variable
var query = $(this).val();
// call to an ajax function
$.ajax({
// assign a controller function to perform search action - route name is search
url:"{{ route('admin.search') }}",
// since we are getting data methos is assigned as GET
type:"GET",
// data are sent the server
data:{'vendor':query},
// if search is succcessfully done, this callback function is called
success:function (data) {
// print the search results in the div called vendor_list(id)
$('#vendor_list').html(data);
}
})
// end of ajax call
});
// initiate a click function on each search result
$(document).on('click', 'li', function(){
// declare the value in the input field to a variable
var value = $(this).text();
// assign the value to the search box
$('#vendor_id').val(value);
// after click is done, search results segment is made empty
$('#vendor_list').html("");
});
});
</script>
Route
Route::get('search', 'PurchasedOrderController#search')->name('search');
Can you help me fix the dropdown list and also display the vendor_name on vendor name input field once the this click code trigger? Thank you so much in advance!!!
For me your problem comes from your controller and you need a post request too or stay in get and do like that.
Controller
public function search(Request $request, $vendor){
// check if ajax request is coming or not
if($request->ajax()) {
// select country name from database
$data = Vendor::where('vendor_id', 'LIKE', '%'.$vendor.'%')
->get();
// declare an empty array for output
$output = '';
// if searched countries count is larager than zero
if (count($data)>0) {
// concatenate output to the array
$output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
// loop through the result array
foreach ($data as $row){
// concatenate output to the array
$output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
}
// end of output
$output .= '</ul>';
}
else {
// if there's no matching results according to the input
$output .= '<li class="list-group-item">'.'No results'.'</li>';
}
// return output result array
return $output;
}}
Your route
Route::get('search/{vendor}', 'PurchasedOrderController#search')->name('search');
Your blade
$(document).ready(function () {
// keyup function looks at the keys typed on the search box
$('#vendor_id').on('keyup',function() {
// the text typed in the input field is assigned to a variable
var query = $(this).val();
// call to an ajax function
$.ajax({
url:"yourdomain.com/search/"+query,
// since we are getting data methos is assigned as GET
type:"GET",
// if search is succcessfully done, this callback function is called
success:function (data) {
// print the search results in the div called vendor_list(id)
$('#vendor_list').html(data);
}
})
// end of ajax call
});
It should work, also not in post you have to change in your controller your $request->vendor_id it is not good, change to $request->vendorand pass your route laravel and the ajax request in post and it should work
for onclick:
$('#list-group-item').on('click', function(){
var item_select = $(this).text();
$('#vendor_id').val(item_select);
$('#vendor_list').html("");
});
Related
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();
});
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 have a table created using a while loop thats displays a list of items so that the user can select an item to delete which is done via ajax.
I would like to use JQuery's closest attribute but I can't work out the correct syntax. The output I get from this is Object Object
The table
<form id="del_opinion">
<table id="asked_list">
<?php
while($row = mysqli_fetch_assoc($result)){
<tr>
<td>
<?php echo $row['name']; ?>
</td>
<td>
<input type="button" name="del_question" value="" class="trash_btn">
<input type="hidden" class="id_question" name="question_id" value="<? echo $row['questionID']; ?>">
<input type="hidden" class="id_user" name="user" value="<?php echo $id; ?>" >
</td>
</tr>
<? } ?>
</table>
</form>
The ajax
<script>
$(document).ready(function() {
$('.trash_btn').click(function(){
var question = $(this).closest('.id_question');
var user = $(this).closest('id_user');
$.ajax({
url: 'opinion_del.php',
type:'POST',
data: 'question='+ question +'&user='+user,
dataType: 'json',
success: function(response){
$('#responses_table').html(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
The php have done for testing
$question_id = $_POST['question'];
$id = $_POST['user'];
$sql = "SELECT * FROM adviceQuestion WHERE questionID = '$question_id'";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
if($result){
$output = $question_id;
}
echo json_encode($output);
If I type a literal value to $output it works fine and if I type a literal value in either of the jquery vars they work correctly too so I'm convinced it is something to do with the closest syntax
I have also tried adding a class to the table row called details and using
var question = $(event.target).closest('.details').find('.id_question');
If I alert question it says [object Object]
var user = $(this).closest('id_user');
Change to this
var user = $(this).closest('.id_user');
You didnt specified a c lass "." dot ))) Maybe will help
OK, sussed it...
Changed this
var question = $(this).closest('.id_question');
var user = $(this).closest('id_user');
to
var question = $(this).next('.id_question').val();
var user = $(this).next('.id_user').val();
<script type="text/javascript">
function addField(){
var newContent = "<li><input type='text' name='mytextfield[]'/></li>";
$("#myfields").append(newContent);
}
</script>
<input type='text' name='mytextfield[]' />
<div id='addmorelink'>
<a href='javascript:addField()'>add more contact</a>
</div>
This is my view code... I need to fetch the data from input field 'mytextfield[]' which is a dynamic field.
when you are posting array data in your controller you should take it as post array like this
function add_records()
{
//this $name is array
$name = $this->input->post('name');
//you can use a foreach loop to insert these data to the data base or you can use
//codeigniter insert_batch function
}
Use
$contacts = $this->input->post('mytextfield');
foreach($contacts as $key=>$val){
// process them as you like
}
I'd made a form using CI and have a native form_validation() library to validate each fields input, I using jQuery post to callback the input to check whether each fields is valid, how if I want each error to populate into form_error() next to each field instead of validation_errors()?
Please refer to below:
view:
<script>
$("#btnregister").click(function() {
var parameters = $("#reg_form").serialize();
$.post(baseurl+'pages/registration', parameters, function(data) {
if(data == "ok") {
//show success message
}else{
$("#error").html(data);
}
}, "html");
});
</script>
<div id="error"></div>
<form id="reg_form" method="post">
<p>
<label for="reg_username">Username</label><br />
<input type="text" id="reg_username" name="reg_username" value="<?php echo set_value('reg_username'); ?>">
<?php echo form_error('reg_username'); ?>
</p>
<p>
<label for="reg_email">Email</label><br />
<input type="text" id="reg_email" name="reg_email" value="<?php echo set_value('reg_email'); ?>">
<?php echo form_error('reg_email'); ?>
</p>
<p><input type="button" id="btnregister" value="Register"></p>
</form>
</div>
Controller:
public function registration(){
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if($this->form_validation->run() == FALSE){
echo validation_errors();
}else{
// insert to db
echo "ok";
}
}
Thanks for help.
You'll have to build your own error array. It would be nice if we could access the
Form_validation's $_error_array but unfortunately it's protected and there's no access method for it.
I'm going to change your controller to output a json response to make this easier:
public function registration()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
$this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
if ($this->form_validation->run())
{
$response['status'] = TRUE;
}
else
{
$errors = array();
// Loop through $_POST and get the keys
foreach ($this->input->post() as $key => $value)
{
// Add the error message for this field
$errors[$key] = form_error($key);
}
$response['errors'] = array_filter($errors); // Some might be empty
$response['status'] = FALSE;
}
// You can use the Output class here too
header('Content-type: application/json');
exit(json_encode($response));
}
Now your ajax success callback can read the status and errors keys of the response. You can loop through data.errors and add each one to the input field:
$("#reg_form").submit(function() {
var form = $(this);
$.post(baseurl+'pages/registration', form.serialize(), function(data) {
if (data.status == true) {
//show success message
}else{
$.each(data.errors, function(key, val) {
$('[name="'+ key +'"]', form).after(val);
});​
}
}, "json");
});
Another easy way is to post the form to itself, and have your ajax response reload the entire form - that way the messages and validation filters will be taken care of server-side.