Autocomplete doesn't work with mysql - php

Okay I am using prepared statement to get all the cities.
this is my php file
<?php
include_once '../includes/db_connect.php';
$search = $_GET['term'];
if($stmtgetstore = $mysqli->prepare("SELECT * FROM cities WHERE city LIKE '%$search%'"))
{
//$stmtgetstore->bind_param("s",$search);
$stmtgetstore->execute();
$getstore = $stmtgetstore->get_result();
$stmtgetstore->close();
}
else
{
echo $mysqli->error;
}
$array = array();
$json = '[';
$first = true;
while($store = $getstore->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$store['city'].'"}';
}
$json .= ']';
?>
And this is my script and html
<script type="text/javascript">
$(document).ready(function()
{
$('#autoCity').autocomplete(
{
source: "scripts/search_store_by_city.php",
minLength: 2
})/*.data( "autocomplete" )._renderItem = function( ul, item )
{
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.city )
.appendTo( ul );
};*/
});
</script>
<div class="container">
<form action="" method="GET">
<input type="text" id="autoCity">
</form>
</div>
But somehow when I enter letters in textbox I see no result coming in console and no error also but when I run query in database it gives me rows
This query
SELECT * FROM cities WHERE city LIKE '%Kara%'
Any idea what me doing wrong?

Okay I forgot to echo my json at the end of the script
<?php
include_once '../includes/db_connect.php';
$search = $_GET['term'];
if($stmtgetstore = $mysqli->prepare("SELECT * FROM cities WHERE city LIKE '%$search%'"))
{
//$stmtgetstore->bind_param("s",$search);
$stmtgetstore->execute();
$getstore = $stmtgetstore->get_result();
$stmtgetstore->close();
}
else
{
echo $mysqli->error;
}
$array = array();
$json = '[';
$first = true;
while($store = $getstore->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$store['city'].'"}';
}
$json .= ']';
echo $json;
?>

Related

Event not triggering until 3rd click

I have a filter by alphabet within a WordPress website that I would like to filter when the letter is selected without the user having to select the letter and then the search button. However it only seems to work after the 3rd click and that is if you click quickly. The filter itself is a customisation for an existing WordPress directory theme, here is a link to the directory: https://staging.pata.org.uk/item/. How can I get the click to trigger on the first click of a letter rather than the third?
This is the jquery:
<script type="text/javascript">
jQuery(document).ready(function(){
// filter type actions
// checkbox
jQuery('.advanced-filters-wrap-letter ul li.filter-checkbox-letter').on('click', function(e){
jQuery(this).toggleClass('filter-enabled');
var $input = jQuery(this).find('input');
if($input.is(':checked')){
$input.removeAttr('checked');
} else {
$input.attr('checked', true);
}
// filter submit actions
jQuery('.filter-container').on('click', function(e){
e.preventDefault();
// build new query
var addToFilter = "";
var filterString = "";
var filterCheck = 0;
// &filters=id;id;id
jQuery('.advanced-filters-wrap ul li').each(function(){
var $inputOne = jQuery(this).find('input');
if($inputOne.is(':checked')){
addToFilter = $inputOne.val() + " ";
filterCheck += 1;
}
});
jQuery('.advanced-filters-wrap-letter ul li').each(function(){
var $input = jQuery(this).find('input');
if($input.is(':checked')){
filterString = filterString + $input.val() + " " + addToFilter;
filterCheck += 1;
}
});
filterString = filterString.trim().replace(new RegExp(' ', 'g'), ";");
var pathName = window.location.pathname;
/* remove page parameter from url */
pathName = pathName.replace(new RegExp("page\/[0-9]*\/", 'g'), "");
/* remove page parameter from url */
var baseUrl = window.location.protocol+"//"+window.location.host+pathName;
var eParams = window.location.search.replace("?", "").split('&');
var nParams = {};
jQuery.each(eParams, function(index, value){
var val = value.split("=");
if(typeof val[1] == "undefined"){
nParams[val[0]] = "";
} else {
nParams[val[0]] = decodeURIComponent(val[1]);
}
});
var query = jQuery.extend({}, nParams, { filters: filterString });
if(filterCheck == 0){
delete query.filters;
}
delete query.paged;
delete query.count;
// remove empty keys
jQuery.each(query, function(k, v){
if(!k){
delete query[k];
}
});
var queryString = jQuery.param(query);
window.location.href = baseUrl + "?" + queryString;
});
});
});
</script>
and this is the rest of the code
<?php
// &filters=id;id;id;id
$themeOptions = aitOptions()->getOptionsByType('theme');
$advancedFiltersOptions = (object)$themeOptions['itemAdvancedFilters'];
if($advancedFiltersOptions->enabled){
$filters_avalaible = get_terms('ait-items_filters', array('hide_empty' => false));
$filters_enabled = array();
if(isset($_REQUEST['filters']) && !empty($_REQUEST['filters'])){
$filters_enabled = explode(";",$_REQUEST['filters']);
}
if($query->max_num_pages != 1){
// check if there will be pagination
$item_query_args = $query->query_vars; // populate new variable ... dont modify original query
$item_query_args['nopaging'] = true;
$item_query = new WP_Query($item_query_args);
} else {
$item_query = $query;
}
$item_filters = array();
foreach($item_query->posts as $post){
$post_meta = get_post_meta( $post->ID, '_ait-item_filters-options');
if(!empty($post_meta)){
$post_filters = $post_meta[0]['filters'];
foreach ($post_filters as $id) {
$filter = get_term($id, 'ait-items_filters', "OBJECT");
if(!empty($filter)){
array_push($item_filters, $filter);
}
}
}
}
$unique_filters = array_map("unserialize", array_unique(array_map("serialize", $item_filters)));
$filters_avalaible = $unique_filters;
usort($filters_avalaible, function($a, $b){
return strcmp($a->slug, $b->slug);
});
?>
<?php
if(is_array($filters_avalaible) && count($filters_avalaible) > 0){
?>
<div class="advanced-filters-wrap-letter">
<div class="advanced-filters-container">
<div class="content">
<h3>Alphabetical</h3>
<ul class="advanced-filters columns-<?php echo $advancedFiltersOptions->filterColumns ?>">
<?php
$array=array("A", "B", "C", "D", "E", "F","G","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
$letters = array();
foreach($filters_avalaible as $filter){
if(in_array($filter->name,$array)) {
array_push($letters, $filter);
}
}
?>
<?php
foreach($letters as $letter)
{
if(!empty($letter))
{
$filter_options = get_option( "ait-items_filters_category_".$letter->term_id );
$filter_type = isset($filter_options['type']) ? $filter_options['type'] : 'checkbox';
$is_enabled = in_array($letter->term_id, $filters_enabled);
$li_class = "";
$in_checked = "";
if($is_enabled){
$li_class = "filter-enabled";
$in_checked = "checked";
}
switch($filter_type){
case 'checkbox':
/*$imageClass = !empty($filter_options['icon']) ? 'has-image' : '';*/
$imageClass = 'has-image';
$image = !empty($filter_options['icon']) ? '<i class="fa '.$filter_options['icon'].'"></i>' : '<i class="fa fa-dot-circle-o"></i>';
echo '<li class="filter-container filter-checkbox-letter '.$li_class.' '.$imageClass.' "><input type="checkbox" name="'.$letter->slug.'" value="'.$letter->term_id.'" '.$in_checked.'> <span class="filter-name">'.$letter->name.'</span></li>';
break;
default:
echo '<li class="filter-container filter-unsupported">'.__('Unsupported filter', 'ait-advanced-filters').'</li>';
break;
}
}}}?>
</ul>
</div>
</div>
<div class="advanced-filters-actions">
<?php _e('Search', 'ait') ?>
Back
</div>
</div>
<?php
}

Get and store id from database to different table based on user search input

I have multiple dynamic textboxes where users input license plate no. I'm trying to retrieve the id corresponding to the license plate # inputted by the user from the database but I'm unable to get it. I want to store the license plate #'s id that's already in the database to a different table and not the license plate no itself, but It always returns null.
Thanks in advance.
search.js
function firetruckAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes2").val();
$('.NewlyCreatedSelectBoxes2').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="firetruck[]" class="search" placeholder="License Plate No" required/><br>';
}
$('.NewlyCreatedSelectBoxes2').append(txtBox);
$(".NewlyCreatedSelectBoxes2").on("keyup", ".search", function () {
var search_term = $(this).val();
$('#search_results2').html('Searching database...');
if (search_term !== '') {
$.post('php/firetruck_search.php', { search_term: search_term }, function (data) {
$('#search_results2').html(data);
});
} else {
$('#search_results2').html('Not Found');
}
});
return false;
}
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fireTruckID`, `licensePlateNo` FROM `firetruckinfo` WHERE `licensePlateNo` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['licensePlateNo'], '</p>';
}
}
}
?>
occurrence.php
$firetrucks = $_POST['firetruck'];
foreach($firetrucks as $firetruck):
$vehicleID = mysql_query("SELECT `fireTruckID` FROM `firetruckinfo` WHERE `licensePlateNo`='$firetruck'");
$row2 = mysql_fetch_assoc($vehicleID);
$query3 = "INSERT INTO `truckonscene`(`FireTruckInfo_fireTruckID`, `IncidenceOfFire_incidentID`)
VALUES(
'".mysql_real_escape_string($row2['fireTruckID'])."',
'".mysql_real_escape_string($incidentid)."')";
mysql_query($query3) or die(mysql_error());
endforeach;

How can I run a mysql query when the user selects an new option in a select field?

I want to have a select box that list categories of products. When a category is selected I want to simultaneously select the products in that category from the database. Do I need to use AJAX with this application? Any examples about doing this? Here is the code I'm working with:
These functions build the options of each select field.
function buildCategoryOptions($catId = 0)
{
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$categories = array();
while($row = dbFetchArray($result)) {
list($id, $parentId, $name) = $row;
if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
} else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id' => $id, 'name' =>
$name);
}
}
// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name = $value['name'];
$children = $value['children'];
$list .= "<option value=\"$key\"";
if ($key == $catId) {
$list.= " selected";
}
$list .= ">$name</option>\r\n";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}
$list .= "> {$child['name']}</option>\r\n";
}
}
return $list;
}
/*
Build the product options list for the radio options
*/
function buildProductOptions($catId = 0)
{
$sql = "SELECT pd_id, pd_name, cat_id
FROM tbl_product
WHERE cat_id = $catId
ORDER BY pd_name";
$result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error());
$numProduct = dbNumRows($result);
$products = array();
while($row = dbFetchArray($result)) {
list($id, $name) = $row;
// we create a new array for each top level categories
$products[$id] = array('name' => $name);
}
// build combo box options
$list = '';
foreach ($products as $key => $value) {
$name = $value['name'];
$list .= "<option value=\"$key\"";
$list .= ">$name</option>\r\n";
}
return $list;
}
This is the page of the select fields:
$catId = (isset($_GET['catId']) && $_GET['catId'] > 0) ? $_GET['catId'] : 0;
$categoryList = buildCategoryOptions($catId);
$productList = buildProductOptions($catId);
<!--- Category Select --->
<select name="cboCategory" id="cboCategory" class="box">
<option value="" selected>-- Choose Category --</option>
<?php
echo $categoryList;
?>
</select>
<!--- Products Select : category is changed the products need to be from selected cat -
-->
<select name="selectOptions" id="selectOptions" class="box" multiple="multiple" >
<option>--Pick the other options--</option>
<?php
echo $productList;
?>
</select>
Yes you do need to use ajax here. Check following code and notes.
Write the function that returns a ActiveXObject() which would do a ajax call as
function getXMLHTTP() {
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
}
return xmlhttp;
}
Then write a function specific to your site that would get the desired data as
function getProducts(){
var select1 = document.getElementById("cboCategory");
var strURL = "getproducts.php?city="+select1.options[select1.selectedIndex].value;
var req = getXMLHTTP(); // function to get xmlhttp object
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) { // data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('productsdiv').innerHTML = req.responseText; // div to be updated
} else {
alert("[GET Products]There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
};
req.open("GET", strURL, true); // open url using get method
req.send(null);
}
}
This function would be called on change event of the cboCategory select options, so the corresponding html would be
<select onchange="getProducts()" id="cboCategory" class="box">
...
</select>
<!-- Can be anywhere on same page -->
<div id="productdiv"> </div>
Your getproduct.php page would return a html as string that would over-write the contents of producstdiv tag in your html page.
You can also return data from php as json. Check it's tag wiki for more info. Also you can use jquery to do ajax call.

Autocomplete: Formatting the results

Let me try ask this again with a code snippet with what I have tried
I'm trying to format a Jquery autocomplete to include a heading for each of the data sources and to highlight the term. I'm using Codeigniter and thought maybe the easiest would be to format it before i send it back:
JS:
$( ".auto-search" ).autocomplete({
source: '/json/autocomplete_search',
minLength: 2,
});
PHP (Codeigniter)
public function autocomplete_search()
{
$term = $this->input->get('term');
//load model and get results
$this->load->model("mymodel");
$results1= $this->mymodel->search_one($term);
$results2= $this->mymodel->search_two($term);
//Start JSON string
$json='[';
//first source
if ($result1->num_rows() > 0)
{
$json .= '{"value":"<h3>Heading One<h3>"}';
foreach ($results1->result_array() as $r1)
{
$result = str_replace($term,"<strong>".$term."</strong>",$r1['title']);
$json .= ',{"value":"'.$result.'"}';
}
}
//second source
if ($result2->num_rows() > 0)
{
if ($result1->num_rows() > 0){$json .= ',';}
$json .= '{"value":"<h3>Heading Two<h3>"}';
foreach ($results2->result_array() as $r2)
{
$result = str_replace($term,"<strong>".$term."</strong>",$r2['location']);
$json .= ',{"value":"'.$result.'"}';
}
}
//Close JSON string
$json .= ']';
echo $json;
}`
Unfortunately I'm not getting a formatted output, instead, it actually adds the words < h1> and < strong> to the output. Here is sample output:
Okay so I've found a way to do it. Here is how I did it:
Javascript:
$( ".auto-search" ).autocomplete({
source: '/hotpepper/json/autocomplete_search2',
minLength: 2,
open: function(event, ui) {
$(".ui-autocomplete .ui-menu-item a").each(function (i) {
var row = $(this).html();
row=row.replace(/</g,"<");
row=row.replace(/>/g,">");
$(this).html(row);
});
},
});
PHP(Codeigniter):
public function autocomplete_search2()
{
$term = $this->input->get('term');
//load model and get results
$this->load->model("establishment_model");
$results1= $this->establishment_model->search_autocomplete_est($term);
$results2= $this->establishment_model->search_autocomplete_loc($term);
//Start JSON string
$json='[';
//first source
if ($results1->num_rows() > 0)
{
$header= "<h3 style='font-weight:bold'>Accommodation:</h3>";
$json .= '{"value":"'.$header.'"}';
foreach ($results1->result_array() as $r1)
{
$result = str_replace($term,"<strong style='color:#C00'>".$term."</strong>",$r1['establishment_name']);
$json .= ',{"value":"'.$result.'"}';
}
}
//second source
if ($results2->num_rows() > 0)
{
if ($results1->num_rows() > 0){$json .= ',';}
$header= "<h3 style='font-weight:bold'>Destinations:</h3>";
$json .= '{"value":"'.$header.'"}';
foreach ($results2->result_array() as $r2)
{
$result = str_replace($term,"<strong style='color:#C00'>".$term."</strong>",$r2['establishment_location']);
$json .= ',{"value":"'.$result.'"}';
}
}
//Close JSON string
$json .= ']';
echo $json;
}
Since auto-complete escapes my html that I send through, I just unescape it by replacing < and > with <> when i open the auto complete box.
EDIT:
Also had to add the following event to format the result back:
close: function(event, ui) {
var result = $(this).val();
if (result.search("</h3>") ==-1)
{
result=result.replace(/<strong style='color:#C00'>/g,"");
result=result.replace(/<\/strong>/g,"");
}
else
{
result="";
}
$(this).val(result);
}

CKEditor with json not passing content

I am trying to submit a form without leaving the page using json.
However, the method below ignores the data I have entered into the CKEditor.
Any ideas (and feel free to correct my terminology)?
<script type="text/javascript">
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
</script>
<form name="addStory" action="" method="post" id="addStory">
<label for="story_story">Story: </label><textarea id="story_story" name="story_story"><p></p></textarea>
<?php
// Include the CKEditor class.
include("ckeditor/ckeditor.php");
// Create a class instance.
$CKEditor = new CKEditor();
$CKEditor->basePath = '/ckeditor/'
$CKEditor->replace("story_story");
?>
<input type="submit" value="Submit" />
</form>
_posteddata.php:
include 'connection.php';
function check_input($value, $quoteIt)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (is_null($value) || $value=="") {
$value = 'NULL';
} else if (!is_numeric($value) && $quoteIt == 1) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// CKEDITOR STUFF FOR STORY_STORY
if (isset($_POST)) {
$postArray = &$_POST;
}
foreach ( $postArray as $sForm => $value )
{
if($sForm == "story_story") {
$story_story = check_input($value, 1);
}
}
$query = "INSERT INTO story_table (story) VALUES ($story_story)";
mysql_query($query) or die(mysql_error() . $query);
$return = array();
$return['adminList'] = "New story added with ID: " . mysql_insert_id();
header('application/json');
echo json_encode($return);
mysql_close();
In this kind of situation you must force CKEditor to update the contents of the textarea
So your function would be something like this:
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
CKEDITOR.instances.story_story.updateElement(); // Update the textarea
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});

Categories