I am trying to implement xeditable plugin select2 with emote data fetch from my database , my data fetch script is returning the json data but the ajax call is not retrieving it . my code looks like the following:
HTML
found by ID
Javascript
$('#username ').editable({
type: 'select2',
url: '../payments/person.php',
pk: 1,
onblur: 'submit',
emptytext: 'None',
select2: {
placeholder: 'Select a Requester',
allowClear: true,
width: '230px',
minimumInputLength: 3,
id: function (e) {
return e.person_id;
},
ajax: {
url: '../payments/person.php',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (employee) {
return employee.name;
},
formatSelection: function (employee) {
return employee.name;
},
initSelection: function (element, callback) {
return $.get('../payments/person.php', { query: element.val() }, function (data) {
callback(data);
}, 'json'); //added dataType
}
}
});
Php code returns the data in json format like below:
[{"id":"1","name":"AdminAdmin"}]
I am sure my ajax code is not collecting the data properly , and when i click on it it doesnt load the popup as well. if someone could help.
my php code for fetching look like the following:
if (isset($_POST['person_id'])) {
$id = trim($_POST['person_id']);
$result = array();
$id = mysqli_real_escape_string($con,$id);
$res = mysqli_query($con,"SELECT person_id,Concat(first_name ,last_name) as name FROM k_people ");
while ($row = mysqli_fetch_array($res)) {
$result[] = array(
'id' => $row['person_id'],
'text' => $row['name']
);
}
echo json_encode($result);
}
I think [{"id":"1","name":"AdminAdmin"}] should be [{"id":"1","text":"AdminAdmin"}].
Related
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'].
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
};
}
}
});
I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});
I am trying to display select 2 search ajax results with groups. But it doesn't display any results. I am using WordPress Ajax for this.
Here is my JS code ,
jQuery('select.select2-group_filters-dropdown').select2({
//placeholder: "Select pages / post / categories",
ajax: {
url: ajaxurl,
dataType: 'json',
method: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
action: 'cp_get_posts_by_query'
};
},
results: function (data, page) {
return {results: data};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 0,
});
data I am returning from PHP as,
$searchString = $_POST['q'];
$childdata = array();
$query = new WP_Query( array( 's' => $searchString ) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$title = get_the_title();
$ID = get_the_id();
$childdata[] = array('id' => "post-".$ID, 'text' => $title );
}
} else {
$data[] = array('id' => '0', 'text' => 'No results Found');
}
$data = array(
"text" => "posts",
"children" => $childdata
);
wp_reset_postdata();
// return the result in json
echo json_encode( $data );
die();
This is not running as expected. It returns zero results. Please help me with this.
If you are getting the data from the back end then the problem is in select2 configuration.
Try to make ajax call first and then populate select2 with data. Somethong like this (not sure that will work for you, I cannot test it here):
jQuery.ajax({
url: ajaxurl,
dataType: 'json',
method: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
action: 'cp_get_posts_by_query'
}
}
}).done(function( data ) {
jQuery('select.select2-group_filters-dropdown').select2({ data:data, minimumInputLength: 0});
});
$('.select2').select2({
allowClear: true,
ajax: {
url: function (params) {
return "api/endpoint/?user=" + params.term;
},
dataType: 'json',
delay: 500,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
/* NOTE: return in this format i.e.
* key = **text** : value = username
* key = **id** : value = id
*/
text: item.username,
id: item.id
}
})
};
},
minimumInputLength: 1,
minimumInputLength: 3,
cache: true,
escapeMarkup: function (markup) {
return markup;
},
templateResult: function (item) {
return item.username;
},
templateSelection: function (item) {
return item.username;
},
}
});
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