How to store data from html page to the database? - javascript

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?

Related

Ajax Pagination off the click if li is disabled

I want to off the click when the First Page and Previous li is disabled also when you are on last page the Next and Last should be not clicked. I used off() and unbind() it is working to off the click but when the li is enabled then the click is not working. You can check it here on this link my project is live here http://199.192.21.232/~admin/category.php?cat_id=2 thank you.
HTML Code
<ul class="pagi cf">
<li><strong id="nav_info"></strong></li>
<li id="nav_first"><a>‹‹ First Page</a></li>
<li id="nav_prev"><a>Previous</a></li>
<select class="btn" id="nav_currentPage"></select>
<li id="nav_next"><a>Next</a></li>
<li id="nav_last"><a>Last ››</a></li>
</ul>
Ajax Script
<script>
$(document).ready(function(e) {
//SHOW LIST WHEN DO STRING SEARCH
$("#src-btn").click(function() {
showList('');
});
//--- start navigation btn
$("#nav_first").click(function(e) {
showList('first');
});
$("#nav_prev").click(function(e) {
showList('prev');
});
$("#nav_next").click(function(e) {
showList('next');
});
$("#nav_last").click(function(e) {
showList('last');
});
$("#per-page").change(function(e) {
showList('');
});
$("#nav_currentPage").change(function(e) {
showList('goto');
});
//--- end navigation btn
//SHOW LIST WHEN CALLED BY OTHER BUTTON [ADD NEW ITEM, THEN RELOAD LIST]
$("#src-frm").submit(function() {
showList();
return false;
});
//START SHOWING LIST
showList('');
function showList(navAction) {
$('body').append('<div class="pgrs"></div><div class="spin"><div class="loader">Loading...</div></div>');
//$("#nav_info").html('<div class="loader"></div>');
var searchKeyword = $("#src-txt").val(),
currentPage = $("#nav_currentPage").val(),
rowsPerPage = $("#per-page").val();
$.ajax({
type: 'POST',
url: "pagination.php",
data: {
cat_id: < ? php echo $_GET['cat_id']; ? > ,
keyword : searchKeyword,
currentPage: currentPage,
rowsPerPage: rowsPerPage,
navAction: navAction
},
// this part is progress bar
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
//$('.pgrs').text(percentComplete + '%');
$('.pgrs').css('width', percentComplete + '%');
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
//$('.pgrs').text(percentComplete + '%');
$('.pgrs').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(data) {
//parse json string to javascript json object
var data = JSON.parse(data);
//push data to table
$("#category-products").html(data.list);
//select or focus the target page
$("#nav_currentPage").val(data.targetPage);
//check if action is refresh, then reload the GOTO list
if (navAction == 'refresh' || navAction == '') {
//empty the list
$('#nav_currentPage').empty();
//append option item with value to select list
$.each(data.gotoSelectNum, function(key, value) {
$('#nav_currentPage').append($("<option></option>").attr("value", value).text(value));
});
}
//show list page and record info
if (data.totalPages == 0) {
$("#nav_info").html('List Empty');
} else {
$("#nav_info").html('Page ' + data.targetPage + ' of ' + data.totalPages);
$(".pgrs,.spin").remove();
}
//disable or enable pagination button
$.each(data.nav_btn_disable, function(key, jdata) {
if (jdata == 1) {
$("#" + key).removeClass('disabled');
} else {
$("#" + key).addClass('disabled');
}
})
}
});
}
});
</script>
PHP CODE
<?php
include 'config.php';
$currency_symbol = '$';
$conn = OpenCon();
// SCRIPT IN PHP FILE REQUESTED BY AJAX, SEPARATED FILE
$cat_id = $_POST['cat_id'];
$keyword = $_POST['keyword'];
$currentPage = intval($_POST['currentPage']);
$rowsPerPage = $_POST['rowsPerPage'];
$navAction = $_POST['navAction'];
//Applying some condition to SQL
$sql_condition = 'WHERE';
if($keyword<>''){
$sql_condition .= ($sql_condition == 'WHERE' ? '' : ' FIND_IN_SET('.$cat_id.', products_cat.id) AND')." (product_title LIKE '%$keyword%')";
}
if($sql_condition == 'WHERE'){
$sql_condition = 'WHERE FIND_IN_SET('.$cat_id.', products_cat.id)';
}
//Work with total page
//$query = "SELECT * FROM products $sql_condition ORDER BY product_title ASC";
$query = "SELECT * FROM products_cat JOIN products ON FIND_IN_SET(products_cat.id, products.product_category) $sql_condition ORDER BY products.product_title ASC";
$navRow_qry = mysqli_query($conn,$query);
$totalRow = mysqli_num_rows($navRow_qry);
$totalPages = $totalRow/$rowsPerPage;
if($totalRow%$rowsPerPage>0){$totalPages = intval($totalPages) + 1;}
//Get the target page number
$targetPage = 1;$nav_btn_disable = array();
if($navAction=='first'){
$targetPage = 1;
}elseif($navAction=='prev'){
$targetPage = $currentPage-1;
}elseif($navAction=='next'){
$targetPage = $currentPage+1;
}elseif($navAction=='last'){
$targetPage = $totalPages;
}elseif($navAction=='goto'){
$targetPage = $currentPage;
}
//Get goto select list
$gotoSelectNum = array();
for($i=1;$i<=$totalPages;$i++){
$gotoSelectNum[] = $i;
}
//Check button to be disable or enable
if($totalPages==1 or $totalPages==0){
$nav_btn_disable = array('nav_first'=>0,'nav_prev'=>0,'nav_next'=>0,'nav_last'=>0);
}elseif($targetPage==1){
$nav_btn_disable = array('nav_first'=>0,'nav_prev'=>0,'nav_next'=>1,'nav_last'=>1);
}elseif($targetPage==$totalPages){
$nav_btn_disable = array('nav_first'=>1,'nav_prev'=>1,'nav_next'=>0,'nav_last'=>0);
}else{
$nav_btn_disable = array('nav_first'=>1,'nav_prev'=>1,'nav_next'=>1,'nav_last'=>1);
}
//Applying data to be shown according to the criteria [targetPage,rowsPerPage]
$startIndex = ($targetPage-1)*$rowsPerPage;
$dataListString = '';$i=$startIndex+1;
//Querying data from data
//$query = "SELECT * FROM products $sql_condition ORDER BY product_title ASC LIMIT ".$startIndex.",$rowsPerPage";
$query = "SELECT * FROM products_cat JOIN products ON FIND_IN_SET(products_cat.id, products.product_category) $sql_condition ORDER BY products.product_title ASC LIMIT ".$startIndex.",$rowsPerPage";
$data_qry = mysqli_query($conn,$query);
if (!empty($data_qry) && $data_qry->num_rows > 0)
{
$i = 1;
$dataListString .= '<ul id="products" class="products">';
while($data_row = mysqli_fetch_assoc($data_qry))
{
if($i++ % 5 == 0){$last = ' class="last"';}else{$last = '';}
$ids = explode(",", $data_row['product_images']);
$dataListString .= '<li '.$last.'><a href="single.php?product-id='.$data_row['id'].'">';
$dataListString .= getProductImg($ids[0]);
$dataListString .= getProductImg($ids[1]);
$dataListString .= '<div class="ti">'.$data_row['product_title'].'</div>';
if(empty($data_row['product_sprice'])){
$dataListString .= '<span class="sp">'.$currency_symbol.$data_row['product_rprice'].'</span>';
}
else{
$dataListString .= '<span class="sp">'.$currency_symbol.$data_row['product_sprice'].'</span>';
$dataListString .= '<span class="rp">'.$currency_symbol.$data_row['product_rprice'].'</span>';
$dataListString .= '<span class="pr">'.percent($data_row['product_rprice'],$data_row['product_sprice']).'</span>';
}
$dataListString .= '</a></li>';
}
$dataListString .= "</ul>";
}
else
{
$dataListString .='';
}
//check if no data in database, then display 'No Data' message
if($dataListString == ''){$dataListString = 'No Data Found';}
//store all variable to an array
$data = array('list'=>$dataListString,'targetPage'=>$targetPage,'totalPages'=>$totalPages,'gotoSelectNum'=>$gotoSelectNum,'nav_btn_disable'=>$nav_btn_disable);
//convert array to json object, and return it back to ajax
echo json_encode($data);
CloseCon($conn);
I just fixed it with this code.
$(".pagi li").click(function(e){
if (!$(this).hasClass("disabled"))
{
if($(this).is('#nav_first')){
showList('first');
}else if($(this).is('#nav_prev')){
showList('prev');
}else if($(this).is('#nav_next')){
showList('next');
}else if($(this).is('#nav_last')){
showList('last');
}
}
});

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

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

Ui Autocomplete return all values online but in localhost works

I'm trying about 2 days to fix this I will blow my mind I can't anymore..When I am running it in localhost it's just working fine but when I am trying it online its just returns same values...and all values not returns the search term I can't understand why.
Jquery
$(document).ready(function($){
$('#quick-search-input2').autocomplete({
source:'All/home/directsearch.php',
minLength:2,
autoFocus: true,
select: function(event,ui){
var code = ui.item.id;
if(code != '') {
location.href = 'Movies/' + code;
}
},
html: true,
open: function(event, ui) {
$('ul.ui-autocomplete').slideDown(500)('complete');
$(".ui-autocomplete").css("z-index", 1000);
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("" + item.label + "")
.appendTo(ul);
};
});
PHP
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'search';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
$term = stripslashes($_GET ['term']);
$term = mysql_real_escape_string($_GET ['term']);
$a_json = array();
$a_json_row = array();
include '../../connect.php';
/* ***************************************************************************** */
if ($data = $mysqli->query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5")) {
while($row = mysqli_fetch_array($data)) {
$title = $row['title'];
$year = htmlentities(stripslashes($row['year']));
$type = $row['type'];
$customercode= htmlentities(stripslashes($row['link']));
$category= htmlentities(stripslashes($row['category']));
$synopsis= htmlentities(stripslashes($row['synopsis']));
$img= htmlentities(stripslashes($row['img']));
$id= htmlentities(stripslashes($row['id']));
$category = str_replace(" | ",", ", $category);
$shit = "'";
$ltitle = strtolower($title);
if ($type == "DL-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/HD.png">';
}
else if ($type == "Non-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/NonHD.png">';
}
else if ($type == "CAM")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/CAM.png">';
}
else
{
$qualityresponse = "";
}
$stitle = preg_replace("/[^A-Za-z0-9]/", "", $ltitle);
$a_json_row["id"] = $customercode;
$a_json_row["value"] = ''.$term.'';
$a_json_row["label"] = '
'.$qualityresponse.'<span class="titles">'.$title.'</span><p>'.$year.'</p></center>
';
array_push($a_json, $a_json_row);
}
}
$foundnum = mysql_num_rows(mysql_query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5"));
if ($foundnum == 0)
{
$a_json_row["label"] = '
<li class="ac-no-results ac-item-hover ac-item-selected">No Movies found</li>
';
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
$mysqli->close();
$term = mysql_real_escape_string($_GET ['term']);
to
$term = mysqli->real_escape_string($_GET ['term']);

jquery select2 - Format the results via AJAX php

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();
?>

Categories

Resources