I am using mysql database to retrieve data and show it into Select2. Right now, the search data is being showed in the preview of the get call. But not in the options of the Select2. Even though I am receiving the correct response, i can't get it added into the options of the select box
Below is my Javascript code
$("#selecter").select2({
ajax: {
url: "index.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
});
and here is the php code
if(isset($_GET['q'])){
$urlparam_name = $_GET['q'] ."%";
$link = mysqli_connect('localhost', 'root', '', 'customerdatabase_13030') or die("Error " .mysqli_error($link));
$sql = "
SELECT `customer_13030`.`custID`, `customer_13030`.`name`
FROM `customer_13030`
WHERE `customer_13030`.`custID` like '$urlparam_name' OR `customer_13030`.`name` like '$urlparam_name'
GROUP BY `customer_13030`.`custID` ASC
";
$result = mysqli_query($link, $sql) or die("Error " .mysqli_error($link));
$rows = array();
while ($row = mysqli_fetch_assoc($result))
{
$rows[] =array(
'id' => $row['custID'],
'name' => $row['name']
);
}
echo json_encode($rows);
}
Related
I want to ask how to select default value from ajax to select2? My ajax code:
// Customer
$('.shipper').select2({
placeholder: "Choose Shipper",
selectionTitleAttribute: false,
ajax: {
url: 'getCustomer.php',
dataType: 'json',
data: function (params) {
return {
filter_name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (obj) {
return {id: obj.customer_id, text: obj.name};
})
};
},
cache: true
},
initSelection: function (element, callback) {
return callback({id: "<?php echo $data['customerId']; ?>", text: '<?php echo $shipper['name']; ?>'});
}
});
While my PHP code to fetch data is like this:
<?php
include('config.php');
$json = array();
if (isset($_GET['filter_name'])) {
$clientId = $_GET['filter_name'];
$query = "SELECT * FROM m_customer WHERE c_name LIKE '%$clientId%' AND c_status > 0 ORDER BY c_name ASC LIMIT 0,10";
} else {
$query = "SELECT * FROM m_customer WHERE c_status > 0 ORDER BY c_name ASC LIMIT 0,10";
}
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$json[] = array(
'customer_id' => $row['c_id'],
'name' => strip_tags(html_entity_decode($row['c_name'], ENT_QUOTES, 'UTF-8')),
);
}
echo json_encode($json);
?>
I'm creating update page for my PHP files. So I need this select2 is selected from my database. That's why I get data from database then try to set to initSelection. It's already shows up and selected. But when I press save button (and look at my code from inspect element), the select doesn't have value. So it failed to save (screenshot attached)
I have weird solution:
I put the Option manually with the value and text from DB. It's done! My code become like this:
<select class="shipping form-control" name="shipping_id">
<option value="<?php echo $data['shippingId']; ?>" selected><?php echo $shipping['name']; ?></option>
</select>
But is there any problem/cause further? Because I think it's weird solution... (although it's work)
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I am using select2 and ajax to query my database for terms under a certain taxonomy, but when I search the search boxes just hangs on "searching" without retrieving any results.
This is my html
<select multiple="" name="regions1[]" id="regions1" class="job-manager-multiselect select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"></select>
My jquery:
<script>
jQuery(function($) {
$(document).ready(function() {
$( "#regions1" ).select2({
ajax: {
url: "/ajax/connect.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
// 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
return {
results: data
};
},
cache: true
},
minimumInputLength: 2
});
});
});
</script>
and my php code to query the database, I am looking to get all the term names under the taxonomy "job_listing_region"
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// strip tags may not be the best method for your project to apply extra
layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
// Do Prepared Query
$query = $conn->prepare("
SELECT * FROM (
SELECT wp_terms.name
FROM wp_terms
JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE taxonomy = 'job_listing_region'
AND count = 0
) as T"
);
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['name'], 'text' => $value['name']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
And as you can see, I am retrieving my data, but the search just hangs.
Thanks in advance.
Found the solution here How to load JSON data to use it with select2 plugin
Needed to recreate my results like this
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
}
So you need to change processResults to success and put the following into that function:
for(i=0;1<data.length;++i){
var currentObject = data[i];
var id = currentObject.id;
var text = currentObject.text;
//do what you need to here (Put things in a div, etc)
}
And from there, you can do something like this:
document.getElementById("search").innerHTML = document.getElementById("search").innerHTML+"<br />"+id+text;
I am using the select 2 plugin to search for users. Everything is up an running an my jsons end up with: [{"id":"1","text":"Alex Fagard (afagard) ID: 1"}] .etc.
I am using the following code to build the select 2 interface:
$(document).ready(function(){
$('#username-search').select2({
minimumInputLength: 2,
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
ajax: {
url: "classes/search.class.php?sType=users",
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
});
However I am stuck on how to make it so that when the admin selects a user (aka clicks on their dropdown area) the page redirects to userview.php?id=1 where 1 is the id from the JSON array.
Search function if anyone is interested:
public function searchUsers($term = '') {
if (isset($term)) {
$term = parent::secure($term);
$params = array( ':searchQ' => $term . '%' );
$sql = "SELECT distinct username as suggest, user_id, name
FROM login_users
WHERE username LIKE :searchQ
OR name LIKE :searchQ
OR user_id LIKE :searchQ
ORDER BY username
LIMIT 0, 5";
$stmt = parent::query($sql, $params);
if ( $stmt->rowCount() > 0 ) {
while($suggest = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'id' => $suggest['user_id'],
'text' => $suggest['name'] . ' (' . $suggest['suggest'] . ')' . ' ID: ' . $suggest['user_id'],
);
}
} else {
$data[] = array('id'=>'0', 'text'=>'No results found!');
}
echo json_encode($data);
flush();
}
}
$searchParam = new Search();
if (isset($_GET['term'])) {
// we secure the term before running the search and querying the database
$term = $_GET['term'];
switch (isset($_GET['sType']) ? $_GET['sType'] : NULL) {
case 'users':
$searchParam->searchUsers($term);
break;
case 'levels':
$searchParam->searchLevels($term);
break;
}
}
Version 4.0 +
Events are now in format: select2:selecting (instead of select2-selecting)
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
Came across the same question a year after posting this and googled something and ended up here forgetting I ever posted it in the first place.
Well found a solution:
<script>
$(document).ready(function () {
$("#search").select2({
ajax: {
url: "users.php",
dataType: 'json',
data: function (term) {
return {
term: term,
};
},
results: function (data) {
return {results: data};
}
}
});
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
});
</script>
Event name is select2:selecting
I am having difficulty with properly setting up JSON post to get number of rows from MYSQL database from a php file. I am getting "undefined" alert, when I am looking to alert the number of rows as an integer. I have been using a different stackoverflow post to try to build this Get variable from PHP file using JQuery/AJAX.
Here is the ajax call:
// check number of records in Mine
$.ajax({
url: 'pyrAddToMine.php',
type: 'POST',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
},
error : function () {
alert("error");
}
});
Here is the php code in pyrAddToMine.php:
mysql_select_db($database_cms_test, $cms_test);
$query = "SELECT * FROM $favUserTableName";
$result = mysql_query($query) or die();
$row = mysql_fetch_array($result);
$num_records = mysql_numrows($result);
IF ($num_records >= 15){
$numRec = array(
'ajax' => 'Hello world!',
'numRec' => $num_records,
);
echo json_encode($numRec);
exit;
}
Here are more details on the php file:
<?php
require_once('../Connections/cms_test2.php');
...
mysql_select_db($database_cms_test, $cms_test);
$query = "SELECT * FROM `$favUserTableName`";
$result = mysql_query($query) or die();
$row = mysql_fetch_array($result);
$num_records = mysql_numrows($result);
IF ($num_records >= 15){
$numRec = array(
'ajax' => 'Hello world!',
'numRec' => $num_records,
);
echo json_encode($numRec);
exit;
}
...
?>
Hello you forgot to specify the datatype
$.ajax({
url : 'myAjaxFile.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
},
error : function () {
alert("error");
}
})
if you do not set required options for accepting json, you recieve an string that contain ajax format and you did not recieve an object in javascript
$.ajax({
url: 'pyrAddToMine.php',
type: 'POST',
/* required for accept json for ajax */
accepts:'application/json',
dataType:'json',
/* */
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
},
error : function () {
alert("error");
}
});