Select 2 ajax result with group - php

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;
},
}
});

Related

Problem with json data source on ui autocomplete

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("");
}
}
);
}
});

Select2 v4 Result does not show in the dropdown

What could be wrong in the code below?
I'm using Select2 version 4, when there's no result the No result dropdown shows,
But when there's result nothing shows (The dropdown does not show).
function formatProduct(product) {
if (product.loading) return product.text;
var markup = '<div class="product-to-compare" data=' + product.id + '>' + product.text + '</div>' ;
return markup;
}
function formatProductSelection(product) {
return product.name || product.text;
}
$(".select-category").select2({
ajax: {
url: "/autocomplete",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatProduct,
templateSelection: formatProductSelection
});
In the result from php script I have something like this:
{"items":{"id":12,"text":"Sport"}}
But the dropdown does not show, is there something wrong I'm doing?

xeditable select2 remote data fetching into a select field

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"}].

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

JSON decode php problems

I have index.php and getting problem with to decode the json array.. please help i am new to this..
<script>
$(document).ready(function () {
$("#slider_price").slider({
range: true,
min: 0,
max: 100,
step: 1,
values: [0, 100],
slide: function (event, ui) {
$("#app_min_price").text(ui.values[0] + "$");
$("#app_max_price").text(ui.values[1] + "$");
},
stop: function (event, ui) {
var nr_total = getresults(ui.values[0], ui.values[1]);
$("#results").text(nr_total);
},
});
$("#app_min_price").text($("#slider_price").slider("values", 0) + "$");
$("#app_max_price").text($("#slider_price").slider("values", 1) + "$");
});
function getresults(min_price, max_price) {
var number_of_estates = 0;
$.ajax({
type: "POST",
url: 'search_ajax.php',
dataType: 'json',
data: {
'minprice': min_price,
'maxprice': max_price
},
async: false,
success: function (data) {
number_of_estates = data;
}
});
return number_of_estates;
}
And search_ajax.php
<?php
require_once('includes/commonFunctions.php');
// take the estates from the table named "Estates"
if(isset($_POST['minprice']) && isset($_POST['maxprice']))
{
$minprice = filter_var($_POST['minprice'] , FILTER_VALIDATE_INT);
$maxprice = filter_var($_POST['maxprice'] , FILTER_VALIDATE_INT);
$query = mysql_query("SELECT * FROM cars WHERE min_range >= $minprice AND max_range <= $maxprice");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows);
}
?>
and the problem is i just want to print $rows in specific div "number_results".. how to decode that json array?
are you sure about the data you are passing is in json format
i think it should be
'{"minprice": "min_price", "maxprice":"max_price"}'
you cannot just return ajax returned value from a function since ajax is async...the function will already return number_of_estates , by the time ajax call completes.
use callback or just call a function and append your returned text there
..
stop: function( event, ui ) {
getresults(ui.values[0], ui.values[1]);
},
...
function getresults(min_price, max_price)
{
var number_of_estates = 0;
$.ajax({
type: "POST",
url: 'search_ajax.php',
dataType: 'json',
data: {'minprice': min_price, 'maxprice':max_price},
async: false,
success: function(data)
{
number_of_estates = data;
$("#results").text(number_of_estates);
}
});
}
however ajax is called each time the stop funnction occurs so be careful.

Categories