how to create Loading remote data search in Laravel 5.2? - php

This website is Book Hotel, After a user search to see the city and hotel.
I want to use Loading remote data select2 in laravel 5.2.
Github examples: https://select2.github.io/examples.html#data-ajax
Model City:
protected $fillable = [
'name', 'state', 'country', 'status'
];
Model Hotel:
protected $fillable =[
'name', 'address', 'phone', 'status', ...
];
HTML:
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Script:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
How to write in Laravel controller after send data from ajax?

HTML:
<select id="hotel" name="hotel">
<option value="hotel1">Hotel1</option>
<option value="hotel2">Hotel2</option>
</select>
Jquery and Ajax:
$(document).on('click','#hotel',function(e)
{
e.preventDefault();
var name=$(this).val('hotel');
$.ajax({
type:"POST",
url: "{{url('/controller/search')}}",
data: {
"_token": "{{ csrf_token() }}"
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('ok');
}
}
});
});
Laravel Controller:
public function search(Request $request)
{
$hotel=Hotel::where(['name',$request->name])->first();
return Response::json(array('status'=>TRUE,'hotel'=>$hotel));
}

Related

Changing autocomplete function to display as dropdown list

I have a form where the country states have to be displayed in a dropdown, since there was autocomplete already added, I'm getting the response as array in "console.log(data)" but only when I search a state, however I'm unable to change the autocomplete to selection list, I did attempt by changing jquery autocomplete to use select2,selectmenu or on change, but this only works with autocomplete. I do not require the autocomplete search at all but just the dropdown with the country states to be listed from data. below is the code where I'm using a ajax post to get the response using a api call from php file. how do I get the list of country states in selection list and trigger an event when selected, I'm a newbie in this domain.
Some of the sources that I followed,
jQuery autocomplete + ajax API call only triggers list on spacebar/down arrow?
jQuery Autocomplete, passing success data to the select method
html -
<select id = "country_state"></select>
jquery -
('#country_state').autocomplete({
source: function(request, response) {
Request.AbortAll();
$.ajax({
type: "POST",
minLength: 3,
url: base_path + "countrystatelist.php",
dataType: "json",
data: {
q: request.term
},
beforeSend: function (jqXHR, settings) {
Request.List.push(jqXHR);
},
success: function(data) {
response(data);
console.log(data);
}
});
},
select: function(event, ui) {
$('#country_state').attr('country_state-id', ui.item.id);
}
});
php -
public function AllState() {
$results = [];
$Country_states_info = CountryState::GetAllStates(); /* from api */
foreach ($Country_states_info as $country_state) {
if (!isset($country_state['name'])) {
continue;
}
$results[] = [
'value' => $country_state_name,
'label' => $country_state_name,
'id' => $country_state['id'],
];
}
return new JsonResponse($results);
}
using select2
jQuery('#country_state').select2({
source: function(request, response) {
Request.AbortAll();
jQuery.ajax({
type: "POST",
minLength: 3,
url: base_path + "countrylist.php",
dataType: "json",
data: {
q: request.term
},
beforeSend: function (jqXHR, settings) {
Request.List.push(jqXHR);
},
success: function(data) {
// response(data);
return {
results: data.items
};
console.log(data);
}
});
},
select: function(event, ui) {
$('#country_state').attr('country_state-id', ui.item.id);
}
});
Would suggest the following updates to your PHP.
public function AllState() {
$results = [];
$Country_states_info = CountryState::GetAllStates(); /* from api */
foreach ($Country_states_info as $country_state) {
if (!isset($country_state['name'])) {
continue;
}
array_push($results, [
'value' => $country_state['name'],
'label' => $country_state['name'],
'id' => $country_state['id'],
]);
}
return new JsonResponse($results);
}
I did not see where $country_state_name was defined. I suspect you meant $country_state['name'].

Can't attach data to select2 option

I want to make edit form and attach data from database to select2 option. In insert form this select2 option search data in database when we type word by word. I can't attach the data in this select2 option. I want to make this select2 option is fill with the data from database and also can change the data like in insert form. I already try $('#requestor').val($row['requestor']); but the data doesn't appear. Can anyone help me???
<select class="requestor form-control" name="requestor" id="requestor" style="width:700px" required="required">
<option value=""></option>
</select>
//search data in database word by word
$('.requestor').select2({
placeholder: 'Requestor Name',
ajax:{
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
dataType: "json",
delay: 250,
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.ID,
text: item.FullName,
option_value:item.ID
});
});
return{
results: results,
cache: true,
};
},
}
});
function load() {
alert('ok');
//console.log(<?php echo $row['ID']; ?>);
if (<?php echo $row['ID']; ?> != '') {
$('#requestor').val($row['requestor']);
}
}
window.onload = load;
Thank You :)
Your code is very messy. Be more clear like this:
<div class="col-md-12">
<select style="width:100%;" name="requestor[]" id="requestor" class="select2-multiple" multiple></select>
</div>
Then:
var $ajax = $("#requestor");
$ajax.select2({
ajax: {
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return{
search: params.term
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data
};
},
cache: true
},
language: "en",
placeholder: "Requestor Name",
allowClear: true,
minimumInputLength: 3,
maximumSelectionLength: 1,
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
var markup = repo.text ;
return markup;
}
function formatRepoSelection (repo) {
return repo.Name.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");
}
Your Ajax data must be have this format:
data[0]['ID'] = 1; //You must have "ID" key
data[0]['Name'] = 'Name'; //You must have "Name" key
It's easy that's it!
Good luck.

Populating a column from database into select2 via jquery

I'm trying to populate tags from DB into a select2 field. The data is returned in the inspect mode, but not populating in the select2 field.
I have a tags table with the tag_id and tag_name fields. The following is the code from the controller that fetches and returns the tags :
public function getTag()
{
$tag_list = DB::table('tags')
->select('t_name')
->get();
return response()->json(['tag_n' => $tag_list]);
The following is the Jquery that brings back the tags :
<script>
$(document).ready(function() {
$("#catBox").select2({
placeholder:"Select and search",
ajax:{
url: urlTag ,
type: 'GET' ,
dataType: 'json',
delay: 250,
data:function(params){
return{
tag_n:params.term
};
},
processResults:function(response){
return{
results: response
};
},
cache:true
}
});
});
</script>
The route and the route url :
<script>
var urlTag = '{{ route('getTag') }}';
</script>
Route::get('/gettag', [
'uses' => 'PostController#getTag',
'as' => 'getTag'
]);
The data is returned in the inspect mode, but not populating in the select2 field.
The following is the Select tag :
<select class="js-example-basic-multiple" multiple="multiple" name="catBox[]" id="catBox" style ="width:250px">
</select>
return data from a server like this:
[{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}] insted of pass with `{a_tag : [{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}]}`
$("#catBox").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
t_name: term
};
}
},
multiple: true,
ajax: {
url: urlTag ,
dataType: "json",
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});

Add some default options in select2 when dropdown is open in remote data

I am using Select2 with remote data. when i click on drop-down. no option will shows until write in search box.
But i want to show some data when drop-down open.
I am trying it with initselection or data but its initialize when data present in selected value.
$('.countrySelection').select2({
placeholder: "Select Country",
allowClear: true,
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: base_url+'ajax_response/getCountry',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
$(".statenoSelect").select2("val", "");
$(".citynoSelect").select2("val", "");
var more = (page * 2) < data.page
return {
results: data.items,
more: more
};
},
cache: true
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax(base_url+'ajax_response/getCountry?id=' + id, {
dataType: "json"
}).done(function(data) { callback(data['items'][0]); });
}else{
$.ajax(base_url+'ajax_response/getCountry?default=true', {
dataType: "json"
}).done(function(data) { callback(data['items']); });
}
},
data:function(element, callback) {
callback(JSON.parse($(element).attr('data-selection')));
},
formatResult: repoFormatResult,
formatSelection: repoFormatResult,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
}).focus(function () { $(this).select2('open'); });
Its working with ajax, but how can I add options without search anything

Select2 with Ajax + PHP

I am trying to use select2 pulling data using ajax from php back end. I could not figure out the documentation as much as I would like to. I think i probably missed some taken for granted stuffs. Please can you help with a simple example. I started or like this...
html
<select id="select_proj" style="width:10em">
<option value="" selected="selected">Search</option>
</select>
js
$('select').select2();
$("#select_proj").select2({
ajax: {
url: '../app/select_prj.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
select_proj: term, // search term
page: 10
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
In php
$data_wildcardsearch = $_POST['term'];
is throwing error
[Notice: Undefined index: term in b>-----/app/select_prj.php on line 18]
Could you please help? Can you please share a sample code as well?
In data() function you must pass 'term' as a key instead of select_proj.
$('select').select2();
$("#select_proj").select2({
ajax: {
url: '../app/select_prj.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
term: term, // search term
page: 10
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
Then you can get it by:
$data_wildcardsearch = $_POST['term'];
You have post term with key => 'select_proj'.
Change code as below,
$data_wildcardsearch = $_POST['select_proj'];
OR
data: {term: term, page: 10},

Categories