Populate Select2 from function call with AJAX - javascript

I want to populate a select2 dropdown with an AJAX response function with data that will be called whenever the dropdown required for it changes value. I console logged to be sure that the function gets reached, but nonetheless, the instructions are not being ran by the machine:
create.tpl - Holds front-end code
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajaxLeadSearch.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term
};
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
$('.select2lead').on("change", function() {
var value = $(this).val();
// console.log(value);
searchProjectsByLeadID(value);
});
function searchProjectsByLeadID(id){
$('.select2project').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajaxProjectSearch.php',
dataType: 'json',
delay: 250,
data: {
"id": id
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
console.log(id);
}
ajaxProjectSearch.php
<?php
require_once('../../config.php');
$login = new Login();
if (!$login->checkLogin()) {
echo lang($_SESSION['language'], "INSUFFICIENT_RIGHTS");
exit();
}
$db = new Database();
// Select the projects
$query = "
SELECT
ProjectID AS project_id,
ProjectSummaryShort AS project_summary,
FROM
`rapports_projectTBL`
INNER JOIN LeadTBL ON rapports_projectTBL.LeadID=LeadTBL.LeadID
WHERE
ProjectID > 0
AND
rapports_projectTBL.LeadID LIKE :leadId
ORDER BY
ProjectID
ASC
";
$binds = array(':leadId' => $_GET['id']);
$result = $db->select($query, $binds);
$json = [];
foreach ($result as $row){
$json[] = ['id'=>$row['project_id'], 'text'=>$row['project_summary']];
}
echo json_encode($json);
Network output in console
https://i.imgur.com/6ZmGGxa.png
*As we can see, the searchProjectsByLeadID(id) function gets called but we get nothing back. No errors nor any values. The only thing getting transported is the first select box, which fetches lead data upon whats typed in the searchbox. *

RESOLVED
Issue was called by having the SQL query looking for a LIKE rather than a DIRECT MATCH:
WRONG
WHERE
ProjectID > 0
AND
rapports_projectTBL.LeadID LIKE :leadId
CORRECT
WHERE
rapports_ProjectTBL.LeadID=:leadId

Related

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

How to append ajax data into select2

I am using select2 dropdown and I am trying to build it as such that it dynamically displays the leads based on the JSON response.
As u can see in the image below, the text inserted correctly returns a JSON array, however, select2 is not capable of assigning the results into options. Therefore, I am literally quite stuck on what to do from here.
https://i.imgur.com/9OnvJzK.pnghere
I already tried setting a variable equal to the selectbox and appending the data in there, but my editor indicates that the code will be unreachable.
Create.tpl - contains front-end code
{literal}
<script>
$(document).ready(function() {
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
}
});
$('#select2lead').select2({
tags: true,
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
data: function (params) {
var query = {
search: params.term
};
// Query parameters will be ?search=[term]&type=public
return query;
},
processResults: function (data) {
var select2lead = $('#select2lead');
// Tranforms the top-level key of the response object from 'items' to 'results'
return {
results: data.items
}
// var option = new Option(data.name, data.id, true, true);
// select2lead.append(option).trigger('change');
}
}
});
$('#summernote').summernote({
height: 150,
minHeight: null,
maxHeight: null,
focus: true
});
})
</script>
{/literal}
ajax.php - handles the search term and returns JSON
<?php
require_once('../../config.php');
$login = new Login();
if (!$login->checkLogin()) {
echo lang($_SESSION['language'], "INSUFFICIENT_RIGHTS");
exit();
}
$db = new Database();
$query = "
SELECT
LeadID AS lead_id,
REPLACE(CONCAT_WS(' ', LeadInitials, LeadInsertion, LeadLastName), ' ', ' ') AS name,
REPLACE(CONCAT_WS(' ', LeadStreet, LeadStreetNumber, LeadNumberAdjective), ' ', ' ') AS address,
LeadZiPCode AS zipcode,
LeadCity AS city
FROM
`LeadTBL`
WHERE
LeadID > 0
AND
LeadLastName LIKE :leadName
ORDER BY
LeadLastName
ASC
";
$binds = array(':leadName' => $_GET['term'].'_%'.'_%');
$result = $db->select($query, $binds);
$json = [];
foreach ($result as $row){
$json[] = ['id'=>$row['lead_id'], 'name'=>$row['name']];
}
echo json_encode($json);
Issue resolved. Turns out I had to disable "more"; See https://groups.google.com/forum/#!msg/select2/4mDifie32t0/jdJl8KIFN0EJ
Regarding the final code that actually pastes the results into the dropdown properly, see:
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term
};
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

Select 2 "ajax results could not be loaded"

Sorry, but can't find a resolve.
Whenever i try to do some searching, select2 will show 'The results could not be loaded'.
I think my ajax settings is wrong
html:
<select class="js-data-example-ajax form-control" multiple="multiple"></select>
script:
$(".js-data-example-ajax").select2({
ajax: {
url: '#Url.Action("LoadCity", "Addresses")',
dataType: 'jsonp',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1,
});
screen
ADD 08.07.2016
some change ajax settings:
dataType: 'jsonp'
to
dataType: 'json'
and add
type: 'GET',
now no message 'The results could not be loaded', and no results
Base from you last comment. The process result should return an object that has a results key.
So it should be:
return {
results: [{id: 1, text: 'Test'}]
}
I recently encountered the exact same problem using version 4.0.5
This is a known bug in the component solved starting with version 4.0.6
From Github official repository:
Fix AJAX data source error #4356
Updating my local version of the select2 component solved the issue.
I have this working select2, I have implemented this yesterday, It might help you.
select2_common('.accounts','Account & Description');
function select2_common(selector,placeholder)
{
$(selector).select2({
minimumInputLength:2,
placeholder:placeholder,
ajax: {
url: "your_url_here",
dataType: "json",
delay: 200,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data) {
// console.log(data);
return {
results: $.map(data, function(obj) {
if(obj.id!=0){
// console.log(obj);
return { id: obj.id, text: obj.name };
}
else
{return {id: obj.id, text: obj.name}}
})
};
},
cache: true
},
debug:false
});
}
//And your result should be in this form, from your method....
//I am using laravel php framework.
public function getAccountDetail(Request $request)
{
$q = $request->input('q');
$result=[];
if (isset($q) && $q != '') {
/*---------- Search by account code or title ----------*/
$data = DB::table('acc_accounts')->select('acc_id','acc_code','acc_title')
->where('acc_code', 'like', '%' . $q . '%')
->orWhere('acc_title', 'like', '%' . $q . '%')
->limit(10)->orderBy('acc_code')->get();
foreach ($data as $key => $value) {
$new1 = array('id' => $value->acc_id, 'name' => $value->acc_code.' ('.$value->acc_title.')' );
array_push($result,$new1);
}
print(json_encode($result));
}
}

How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. Right now, the only thing being returned is "0". Here is my PHP function:
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbpost = $result['text'];
}
}
Here is my jQuery function:
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(data);
},
error: function(){
},
});
};
You are not getting anything, because you are not printing/echoing anything.
What happens if you try
foreach($results as $result) {
echo $fbpost = $result['text'];
}
You code is not working because you are not print anything on server side. so you can small change in your code like below.
jsonencode is use to return an array of data.
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
$fbpost = array();
foreach($results as $result) {
$fbpost = $result['text'];
}
echo json_encode($fbpost);
exit;
}
in response you json_encodeed data. You can decode and use this data using below function in response callback.
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(jQuery.parseJSON( data ));
},
error: function(){
},
});
};

Categories

Resources