jquery select2 - Format the results via AJAX php - javascript

i use select2, i want to format my results like
name, first.
$("#id").select2({
minimumInputLength : 0,
allowClear: true,
ajax : {
url : "Form/page.php",
dataType : 'json',
data : function (term, page) {
return {
q : term
};
},
results: function (data, page) {
return { results : data.ex};
},
formatResult : function formatResult(ex) {
return '<b>' + ex.name + '</b>';
}
}
});
my php file like
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['text']=$r['name'];
$rows['first']=", ". $r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
how can i do that, thanks

I think the php code has to be like this:
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['name']=$r['name'];
$rows['first']=$r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
So, you pass an array of json objects with an id, name and first.
Change the return of formatResult to:
return '<b>' + ex.name + '</b>, ' + ex.first;

PHP example reposted from the Select2 - source example:
https://github.com/ivaynberg/select2/wiki/PHP-Example
In JS:
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
and in PHP:
<?php
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
?>

Related

Ajax based range search in jquery plugin "Datatables"

I´m using the jquery based table plugin "datatables" and I´m trying to implement an ajax based "range search" between two numbers ("start-date" and "end_date"). These entered values should be used for a query in the MySQL column "order_id".
On the server-sided script (fetch.php) I catch the both values like that.
if(isset($_POST['start_date'], $_POST['end_date'])) {
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
The problem is I can´t see any errors in the console, but after using the number range search no results are displayed.
The "category select menus" (category and category2) are working as expected.
I´ve setted up a test site, maybe you can help me to find the error: Testsite
This is my script:
$(document).ready(function () {
var category = "";
var category2 = "";
var start_date = "";
var end_date = "";
load_data();
function load_data(is_category, is_category2, start_date, end_date) {
console.log(is_category, is_category2, start_date, end_date);
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category,
is_category2: is_category2,
start_date: start_date,
end_date: end_date
},
}
});
}
// Number Range Search
$('#search').click(function () {
console.log($(this).attr('id'), start_date, end_date)
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
load_data('','',start_date, end_date);
}
else {
alert("Both Date is Required");
}
});
// Select Menu id="category"
$(document).on('change', '#category, #category2', function () {
//console.log($(this).attr('id'), category, category2)
if ($(this).attr('id') === "category") {
category = $(this).val();
} else if ($(this).attr('id') === "category2") {
category2 = $(this).val();
}
//
$('#product_data').DataTable().destroy();
if (category != '') {
load_data(category, category2);
}
else {
load_data();
}
});
// Select Menu id="category2"
$(document).on('change', '#category2', function () {
var category2 = $(this).val();
$('#product_data').DataTable().destroy();
if (category2 != '') {
load_data(category, category2);
}
else {
load_data();
}
});
});
fetch.php
//fetch.php
$connect = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxxx");
$columns = array('order_id', 'order_customer_name', 'order_item', 'order_value', 'order_date');
$query = "SELECT * FROM tbl_order WHERE ";
if(isset($_POST['start_date'], $_POST['end_date']))
{
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["is_category"]))
{
$query .= "order_item = '".$_POST["is_category"]."' OR ";
}
if(isset($_POST["is_category2"]))
{
$query .= "order_customer_name = '".$_POST["is_category2"]."' AND ";
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(order_id LIKE "%'.$_POST["search"]["value"].'%"
OR order_customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR order_item LIKE "%'.$_POST["search"]["value"].'%"
OR order_value LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY order_id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = $row["order_id"];
$sub_array[] = $row["order_customer_name"];
$sub_array[] = $row["order_item"];
$sub_array[] = $row["order_value"];
$sub_array[] = $row["order_date"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM tbl_order";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
Thats because the is_category and is_category2 are returning 0. You have probably an if statement on your php like if $_POST[is_category] but you also need to do the same in case there is no category selected. Please share the full php to help you out
on your click function replace load_data(start_date, end_date); with load_data('','',start_date, end_date);

How to store data from html page to the database?

I'm trying to store star rating data though HTML page in database using ajax, php and JavaScript. For some reason it's not working, I've posted all the codes below.
Is there any other option to make star rating dynamic in html page.
here is index.html code
<html>
<body>
<div class="py-2">
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<span class="overall-rating pl-2" property="aggregateRating" typeof="AggregateRating"> (Average Rating <span id="avgrat" property="ratingValue"></span> Based on <span id="totalrat" property="ratingCount"></span> Reviews) <span id="msg"></span> </span> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="rating.js"></script>
</body>
</html>
here is rating.js code
(function ($) {
$.fn.rating_widget = function (options) {
var settings = $.extend({
starLength: "5",
initialValue: "0",
imageDirectory: "http://softhubs.website/img/star.png",
inputAttr: null
}, options);
var el = $(this);
var initVal = settings.initialValue;
var avgVal = parseInt($("#avgrat").text());
var ul = $("<ul>");
ul.addClass("rating_widget");
for (var i = 1; i <= settings.starLength; i++) {
if (i <= avgVal) {
ul.append('<li style="background-image:url(' + settings.imageDirectory + '/star.png);background-position:0px -28px;"><span>' + i + '</span></li>');
} else {
ul.append('<li style="background-image:url(' + settings.imageDirectory + '/star.png)"><span>' + i + '</span></li>');
}
}
ul.insertAfter(el);
el.next("ul").children("li").hover(function () {
$(this).parent().children("li").css('background-position', '0px 0px');
var a = $(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0, a + 1).css('background-position', '0px -28px');
}, function () {
if (initVal == "") {
$(this).children("li").slice(0, initVal).css('background-position', '0px 0px');
} else {
$(this).children("li").css('background-position', '0px 0px');
$(this).children("li").slice(0, initVal).css('background-position', '0px -28px');
}
});
el.next("ul").children("li").click(function () {
var a = $(this).parent().children("li").index($(this));
var attrVal = (settings.inputAttr != '') ? el.attr(settings.inputAttr) : '';
initVal = a + 1;
ajaxPostRating(initVal, attrVal);
});
function ajaxPostRating(val, attrVal) {
$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID=' + attrVal + '&ratingPoints=' + val,
dataType: 'json',
success: function (data) {
if (data.status == "ok") {
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_Number);
} else if (data.status == "no") {
$('#msg').text("You are not allow to rate again.");
$("#msg").addClass("text-danger");
} else {}
},
error: function (xhr) {
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
}
}
}(jQuery));
$(function () {
$("#rating_star").rating_widget({
inputAttr: "postID"
});
});
here is rating.php code
<?php
include_once 'db.php';
if(!empty($_POST['ratingPoints'])){
$postID = $_POST['postID'];
$ratingNum = 1;
$ratingPoints = $_POST['ratingPoints'];
//Check the rating row with same post ID
$prevRatingQuery = "SELECT * FROM post_rating WHERE post_id = ".$postID;
$prevRatingResult = $db->query($prevRatingQuery);
if($prevRatingResult->num_rows > 0):
$prevRatingRow = $prevRatingResult->fetch_assoc();
$ratingNum = $prevRatingRow['rating_number'] + $ratingNum;
$ratingPoints = $prevRatingRow['total_points'] + $ratingPoints;
//Update rating data into the database
$query = "UPDATE post_rating SET rating_number = '".$ratingNum."', total_points = '".$ratingPoints."', modified = '".date("Y-m-d H:i:s")."' WHERE post_id = ".$postID;
$update = $db->query($query);
else:
//Insert rating data into the database
$query = "INSERT INTO post_rating (post_id,rating_number,total_points,created,modified) VALUES(".$postID.",'".$ratingNum."','".$ratingPoints."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
$insert = $db->query($query);
endif;
//Fetch rating deatails from database
$query2 = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = ".$postID." AND status = 1";
$result = $db->query($query2);
$ratingRow = $result->fetch_assoc();
if($ratingRow){
$ratingRow['status'] = 'ok';
}else{
$ratingRow['status'] = 'err';
}
//Return json formatted rating data
echo json_encode($ratingRow);
}
?>
db.php
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'post_rating';
$conn = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
?>
rating.sql
CREATE TABLE IF NOT EXISTS `post_rating` (
`rating_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`rating_number` int(11) NOT NULL,
`total_points` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 = Block, 0 = Unblock'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
it is not working, can anyone guide me to resolve this problem?

Ajax datatables multiple column search

I'm new to js and datables and I'm having a difficulty making single column search into multiple column search. Here's my code:
var dataTable = $('#product_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST",
},
"columnDefs":[
{
"targets":[0,5,7],
"orderable":false,
},
],
});
function load_data(is_suppliers)
{
var dataTable = $('#product_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST",
data:{is_suppliers:is_suppliers}
},
"columnDefs":[
{
"targets":[0,5,7],
"orderable":false,
},
],
});
}
$(document).on('change', '#supplier_filter', function(){
var supplier = $(this).val();
$('#product_data').DataTable().destroy();
if(supplier != '')
{
load_data(supplier);
}
else
{
load_data();
}
});
And the query i used was:
$query = "
SELECT * FROM products
INNER JOIN suppliers
ON suppliers.supplierid = products.supplier
";
$query .= " WHERE ";
if(isset($_POST["is_suppliers"]))
{
$query .= "products.supplier = '".$_POST["is_suppliers"]."' AND ";
}
if(isset($_POST['search']['value']))
{
$query .= '
(productname LIKE "%'.$_POST['search']['value'].'%"
OR category LIKE "%'.$_POST['search']['value'].'%")
';
}
if(isset($_POST['order']))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY productid DESC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
(Edited- added full query except execute and fetch part)I've tried replicating the functions and replacing the values with the column i want and i also added another if(isset) to the query but only one column search will work and the others will show no matching records.

Codeigniter Smiley Not Showing Up In Preview Area

I have created a area where user can type in some text and also add smiley into the text area. smiley helper
How ever when I click on my preview button it does not show the generated smiley.
Question how to make sure on the preview are if has any smiles on
question will show up in preview properly. I use preg_replace_callback on my preview function on controller. and also .replace on script Update I found this on user guide but not sure where to add it on code
Generate the smiles here.
<?php
class Question extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->helper('smiley');
}
public function create() {
$this->load->library('table');
$image_array = get_clickable_smileys(base_url('assets/img/smiley'), 'question');
$col_array = $this->table->make_columns($image_array, 8);
$data['smileys'] = $this->table->generate($col_array);
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');
if ($this->form_validation->run() == true) {
}
$data['page'] = 'question/create';
$this->load->view($this->config->item('config_template') . '/template/template_view', $data);
}
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = $new_data;
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
}
Script On View
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
$.ajax({
url: "<?php echo base_url('question/preview');?>",
type: 'POST',
data: {
question: $('#question').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataType: 'json',
success: function(response){
if (response.success) {
$('#preview').html(response.question);
if ($("#preview").find("pre").length > 0){
var html = $('#preview pre').html().replace(/</g, "<").replace(/>/g, ">");
$('#preview pre').html(html);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
} else {
}
}
});
e.preventDefault();
});
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$(document).ready(function(){
$('#bold').click(function() {
wrapText('question', "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("question", "<i>", "</i>");
});
$('#underline').click(function() {
wrapText("question", "<u>", "</u>");
});
$('#pre').click(function() {
wrapText("question", "<pre>", "</pre>");
});
});
</script>
Got it working
I had to use $data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}

AJAX Custom error handling Code issue

My Code Igniter PHP page returns json_encode query when page is load with success data. I made a json_encode when no records found. But i dont know how to pass my no record error to jQuery
PHP
if (($query->num_rows() > 0) && ($counter > 0)){
echo(json_encode($query->result()));
$counter = 0;
} else {
//return false;
$response["error"] = 1;
$response["error_msg"] = "NO records found";
echo json_encode($response);
}}
JQuery
$.ajax({
url: <? base_url() ?> +'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) { //working
$.each(retdata, function(i) {
$("#main_div").append('<div>' + retdata[i].name + '<br>' + retdata[i].marks+ '</div>');
});
}
});
controller:
public function controller_function()
{
//$query = your get query code
$response = array(
'result' => array(),
'error_msg' => '',
);
if ($query->num_rows() > 0)
{
$response['result'] = $query->result();
}
else
{
$response['error_msg'] = 'NO records found';
}
echo json_encode($response);
}
Javascript:
$.ajax({
url: <? base_url() ?> +'main/data',
dataType: "JSON",
type: "POST",
success: function (retdata)
{
if (retdata.error_msg)
{
alert(retdata.error_msg);
}
else
{
$.each(retdata.result, function (i)
{
$("#main_div").append('<div>' + retdata.result[i].name + '<br>' + retdata.result[i].marks + '</div>');
});
}
}
})

Categories

Resources