I want to add automatic Intellisense (Auto Complete--Filtering Search Result) to a textbox, corresponding to the words that I'm typing in that textbox and the Intellisense is fetched from a database table. How can I achieve this? Can anyone help?
Here is my jQuery code:
$(document).ready(function() {
$('#city').autocomplete({
source:'send.php'
});
});
send.php file given below:
$link=mysqli_connect("localhost","hari","123","hari");
$searchTerm = $_GET['query']; //get search term
$query = $db->query("SELECT fname FROM user WHERE fname LIKE
'%".$searchTerm."%' ORDER BY fname ASC"); //get matched data from user table
while ($row = $query->fetch_assoc()) {
$data[] = $row['fname'];
}
echo json_encode($data);//return json data
Corresponding HTML Code is given below:
<div class="content col-sm-12">
<form>
<h1>Hello!!!</h1>
<input type="text" id="city" name="city" size="20" class="city"
placeholder="Please Enter City or ZIP code"><br><br>
</form>
</div>
You have to include the following scripts in your html page
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
And add the following css in head of your html
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
The mistake you made is the parameter passing with the name term and trying to read with the name query in your php file. In your send.php file change the line
$searchTerm = $_GET['query'];
into
$searchTerm = $_GET['term'];
Try this:
$(document).ready(function() {
$('#city').autocomplete({
source: function( request, response ) {
$.ajax( {
url: "send.php",
dataType: "jsonp",
data: {
query: request.term
},
success: function( data ) {
response( data );
}
} );
},
});
});
I have a recommendation for you, use angular 1 for this, you can simply write that code without additional UI libraries and with much much better performance and issue-free solution.
Add the following parent div to your input element:
Change your input to this:
<input type="text" id="city" name="city" size="20" class="city" ng-model="query" ng-change="fetch()" placeholder="Please Enter City or ZIP code">
Add the following code right under your <input>:
<ul>
<li ng-repeat="text in suggestions">{{ text }}</li>
</ul>
As a basic set up, you need this in your <head> section:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
Finally you will create a new file like in assets directory like "suggestions.js" in your assets directory or somewhere and add this file right before you your </body> tag like this in your template:
<script src="assets/suggestions.js"></script>
The file will have the following lines:
var app = angular.module('myApp', []);
app.controller('suggestionsCtrl', function($scope, $http) {
$scope.suggestions = [];
$scope.query = '';
$scope.fetch = function() {
$http({method: 'POST', url: 'send.php', params: { query: $scope.query } }).
then(function(response) {
$scope.status = response.status;
$scope.suggestions = response.data;
}, function(response) {
/* SOMETHING WENT WRONG WTIH THE CALL DO SOMETHING HERE */
});
};
});
There is very simple set-up/tutorial for Angular 1 here:
https://www.w3schools.com/angular/default.asp
This is not a direct answer but believe me a more efficient answer. Angular 1 and the newer versions save a lot of time and brings performance.
And btw, autocomplete() is not a native jQuery function. Also I do not mention that you need jQuery also for Angular, but I assume it's already added in your template.
Related
I am trying to make a form page in adding new client in a database. The form consist of a selection tag that has options for adding house number. But there are circumstances like house number is not yet placed on the database, so I decided to create a button for adding new house no (using modals).
Form:
<div class="col-md-3 form-group" id="autoload">
<label>
Household: <a data-toggle="modal" data-target="#addHousehold"
style="cursor: pointer; text-decoration: none;">
<i class="fa fa-plus" >Add</i></a>
</label>
<select class="form-control select2" style="width: 100%;">
<option selected="selected">Select Household</option>
<?php foreach($result3 as $row): ?>
<option><?=$row['house_no']?></option>
<?php endforeach ?>
</select>
</div>
Script for adding new house number, and refresh the selection when new house number is successfully added:
$('#addHouseholder').click(function(){
var householder = $('.householder').val()
var street = $('.strsel1').val();
$.ajax({
method: "POST",
url: "insert.php",
data: {householder:householder,street1:street}
}).then(()=>{
$("#autoload").load(" #autoload");
alert('Household Added')
})
This function successfully, the only problem is the division of the selection is deformed. I also forgot to say that I reload the div, but I wonder if it is possible to just reload the selection. I am not sure how to execute this. Looking forward for your help. Thank you very much!
Are you using select2 (https://select2.org/)?
If so, you can use the ability to programmatic control the select.
https://select2.org/programmatic-control/add-select-clear-items
By using:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
You could return the option in the ajax response and populate the select.
You just need to echo json format of your data in insert.php file then modify your js script to
$.ajax({
type: "POST",
url: "path/insert.php",
data: {householder:householder,street1:street},
success: function(data){
// Parse the returned json data
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your json object. Guessing that d.no / d.anyOtherInfo are columns in your data
$('#autoload').children(".orm-control.select2").append('<option value="' + d.no + '">' + d.anyOtherInfo + '</option>');
});
}
});
Good luck.
Edit 1: adding source.
check Populate Select box options on click with Javascript/Jquery with Json data
This has probably been asked before, but after searching for awhile I'm still a bit confused. I'm trying to make a flask app but I'm not too familiar with JQuery itself, but I would like to create an autocomplete widget in my html. However, instead of querying a database I'd like to just use a static list and a regex to get results. I used this as reference.
What I did was:
#app.route('/autocomplete', methods=['GET'])
def autocomplete():
search = request.args.get('q')
#query = db_session.query(Movie.title).filter(Movie.title.like('%' + str(search) + '%'))
#results = [mv[0] for mv in query.all()]
results = ['Beer', 'Wine', 'Soda', 'Juice', 'Water']
return jsonify(matching_results=results)
while keeping the rest of the code:
<head>
<link href="//code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="//code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
<script type="text/javascript">
$(function() {
$("#autocomplete").autocomplete({
source:function(request, response) {
$.getJSON("{{url_for('autocomplete')}}",{
q: request.term, // in flask, "q" will be the argument to look for using request.args
}, function(data) {
response(data.matching_results); // matching_results from jsonify
});
},
minLength: 2,
select: function(event, ui) {
console.log(ui.item.value); // not in your question, but might help later
}
});
})
</script>
</head>
<body>
<div>
<input name="autocomplete" type="text" id="autocomplete" class="form-control input-lg"/>
</div>
</body>
I haven't implemented a regex but I assumed if I typed anything with at least 2 characters I would get a dropdown of the list I wrote above. However, I get nothing. Any ideas on how I can get this autocomplete to work?
I have a form with different fields and with input type="file". I use fileupload jQuery library.
Select file
Call
$('#some_id').fileupload().fileupload(
'send',
{
files: file,
url: widget.options.saveVideoUrl,
}
).success(
//...
(first fileupload called for init)
Try again to select file. Got: No files selected, clear console, etc..
Upd.1
The problem appear in E-commerce framework Magento2 in admin area.
The described form appear in such entity like 'slide-out panel'. It means that there is div block and this block wrapped in aside block using javascript.
<button onclick="jQuery('#new').modal('openModal')" .... >
<span>New</span>
</button>
Here is demo example:
Admin URL: https://iwdagency.com/magento2/admin
Username: admin
Password: admin123
Open Products / Catalog / select any product / click on New category
You should see following panel:
On such panel I've added by php constructor fields:
<div class="admin__field field field-new_video_screenshot " data-ui-id="product-tabs-tab-google-experiment-fieldset-element-form-field-new-video-screenshot">
<label class="label admin__field-label" for="..." data-ui-id="product-tabs-tab-google-experiment-fieldset-element-file-image-label"><span>Preview Image</span></label>
<div class="admin__field-control control">
<input id="...." name="image" data-ui-id="product-tabs-tab-google-experiment-fieldset-element-file-image" value="" title="Preview Image" type="file">
</div>
</div>
Script:
define([
'jquery',
'jquery/ui',
'Magento_Ui/js/modal/modal',
'mage/translate',
'mage/backend/tree-suggest',
'mage/backend/validation'
], function ($) {
'use strict';
$.widget('mage.newDialog', {
_create: function () {
var widget = this;
var newVideoForm = $('#new');
this.element.modal({
type: 'slide',
modalClass: 'mage-new-dialog form-inline',
title: $.mage.__('Create'),
buttons: [{
text: $.mage.__('Create'),
class: 'action-primary',
click: function (e) {
var file = $('#new_screenshot').get(0).files[0];
var result = $('#new_screenshot').fileupload().fileupload(
'send',
{
files: file,
url: widget.options.saveUrl,
}
).success(
function(result, textStatus, jqXHR)
{
var data = JSON.parse(result);
data['url'] = $('#new_url').val();
data['name'] = $('#new_name').val();
data['description'] = $('#new_description').val();
$('#media_gallery_content').trigger('addItem', data);
$('#new').modal('closeModal')
}
);
}
}],
});
}
});
return $.mage.newDialog;
});
I found the problem.
In my case the problem appear after initialization fileUpload library.
When I selected input:file, the library wasn't initialized (read as infected). When I pressed the button, initialization ran and any operations with this input become unavailable.
Solution is following: clone our input before it become infected, than do our operations and at the end replace existing infected input with its healthy copy, created before.
When I try to parse a response from an AJAX request as JSON, I get [object, Object] values instead of the actual ones returned before parsing the response. What could I have done wrong?
I have one script named "apply.php" which has the a short application and an AJAX request called when the user selects a town. There is another script named "suburb.php" which retrieves stored suburbs in the database that are under the selected town. The second script is called when the users selects/changes a town.
In the "apply.php" script I have a JavaScript alert that display the response, which I then parses as JSON. After passing the response, [object, Object] is returned instead of the actual values, thus disabling me from reading the JSON key values.
Using the values without parsing them does not help either. I tried checking for question that relate to my problem without any luck.
Your assistance will be greatly appreciated.
apply.php
<?php
$dbcon = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Accomodation Application</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<style>
form div {
margin-bottom: 20px;
}
</style>
<body>
<div>
<div>
<form>
<p>Refresh</p>
<div><label for="applicant-name">First Name</label><br /><input type="text" name="name" id="applicant-name"></div>
<div><label for="applicant-surname">Surname</label><br /><input type="text" name="surname" id="applicant-surname"></div>
<div><label for="applicant-identity">Smart ID Number</label><br /><input type="text" name="surname" id="applicant-identity"></div>
<div id="town">
<label for="applicant-town">Town</label><br />
<select name="town" id="applicant-town"><option value="0">-- Select Town --</option>
<?php
$towns = mysqli_query($dbcon, "SELECT town_id, town_name FROM towns");
while($town = mysqli_fetch_array($towns)){
$town_id = $town['town_id'];
$town_name = $town['town_name'];
echo("<option value=\"$town_id\">$town_name</option>");
}?>
</select>
</div>
<div id="suburb">
<label for="applicant-suburb">Suburb</label><br />
<select name="suburb" id="applicant-suburb">
<option value="0">-- Select Suburb --</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
</div>
</div>
<script>
$(document).ready(function(){
$('#applicant-town').change(function(){
var suburb_town = $(this).val();
$.ajax({
type: "GET",
url: "suburbs.php",
data: {town: suburb_town}
})
.done(function(data){
alert(data);
var burbs = JSON.parse(data);
alert(burbs); // e.g. [{"1":"Halfway House"},{"2":"Noordwyk"},{"3":"Vorna Valley"}]
$(burbs).each(burbs, function(key, value){
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
});
})
.fail(function(){
alert('There is an error somewhere.');
});
});
});
</script>
</body>
</html>
suburbs.php
<?php
$dbcon = new mysqli (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_GET['town'])){
$town_suburbs = array();
$town_id = htmlspecialchars($_GET['town']);
$suburbs = mysqli_query($dbcon, "SELECT suburb_id, suburb_name FROM suburbs WHERE suburb_town = $town_id");
while($suburb = mysqli_fetch_array($suburbs)){
$suburb_id = $suburb['suburb_id'];
$suburb_name = $suburb['suburb_name'];
$town_suburbs[] = array($suburb_id => $suburb_name);
}
echo json_encode($town_suburbs);
}
?>
Why not use dataType: "json" in your statement ajax?
$.ajax({
type: "GET",
url: "suburbs.php",
data: {town: suburb_town},
dataType: 'json'
})
Thus instead of making an "alert ()" you must make a "console.log" and analyze the content through the Javascript console your browser.
The Alert feature only shows "String" and therefore when attempting that shows you the content. The representation of an object in string is [object]. Therefore instead of console.log occupies alert ().
update: You can use alert (JSON.stringify (data)) to display the string in a alert.
update2: Your code will looks
$.ajax({
type: "GET",
url: "suburbs.php",
data: {town: suburb_town},
dataType: 'json'
})
.done(function(data){
console.log(data)
});
})
So first off from the comments you can see what the issue is. However, you may want to use your "id" for something so with that in mind you could do the following.
$town_suburbs[] = array($suburb_id => $suburb_name);
You could change that to
array_push($town_suburbs, array("id" => $suburb_id, "name" => $suburb_name));
Then on your javascript side...
$(burbs).each(burbs, function(key, value){
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
});
That could change to:
$(burbs).each(function(){
$('#applicant-suburb').append('<option value="'+ this.id +'">'+ this.name +'</option>');
});
Perhaps, it was already saved as [Object Object]?
Ensure that,
to decode a JSON string, use JSON.parse()
to encode a JSON string, use JSON.stringify
Hope this helps.
If your "E.G." is correct, then you are not looping (in javascript) in the correct way.
This:
$(burbs).each(burbs, function(key, value){
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
});
Should not work, because you have to loop an array of objects, therefore you first have to loop the array and, then, the objects:
for (var i = 0; i < burbs.length; ++i) {
$.each(burbs[i], function(key, val) {
$('#applicant-suburb').append('<option value="'+key+'">'+val+'</option>');
});
}
According to your example, you can check this fiddle: http://jsfiddle.net/5yaj7La0/2/
As long as your current output has this structure:
[{"1":"Halfway House"},{"2":"Noordwyk"},{"3":"Vorna Valley"}];
You DON'T need to change your PHP code but if the output is different from that (it shouldn't, though), you may need to change your PHP code too.
HTML output :
(output is related to the fiddle, feel free to edit the names and tag and whatever, the important thing here is the Javascript).
If you get [Object object] by doing :
var burbs = JSON.parse(data);//alerting this will definitely present [Object object]
Then everything seems to be fine.
You are parsing the data and this will be converted to a json object.
If you want to view the response data use :
var burbs = JSON.stringify(data);//converts the object to a string
alert(burbs);
Also probably you want to get the values by accessing the keys of each object within the object array:
//lets imagine this is our response data, which can also be the response data you parsed with JSON.parse(data);
var data = [{"1":"Halfway House"},{"2":"Noordwyk"},{"3":"Vorna Valley"}];
function iterate(data)
{
for(var i=0;i<data.length;i++)
{
for(var i=0;i<data.length;i++)
{
for(var key in data[i])
{
var value = data[i][key];
$('#applicant-suburb').append('<option value="'+key+'">'+value+'</option>');
}
}
}
}
Can the problem be with the fact that you are missing a header() statement in your suburb.php file?
Something like
GET-variable called brand.
A few hours ago when I had not implemented the ajax search box, everything worked fine.
The js part looks like this:
$('.mutliSelect input:checkbox').change(function() {
var brand = $("#brand_select input:checkbox:checked").map(function() {
return this.value;
}).get().join(',');
$(".submit_checkboxes").find("a").attr('href', 'index.php?brand=' + brand);
}).change();
Now, having implemented the ajax search box, the var brand does not seem to get filled with any value anymore.
This is the corresponding part of index.php:
<div class="mutliSelect" id="brand_select">
<ul>
<div class="search_view">
<section class="drop_search">
<input type="text" placeholder="Suche" id="search_brand" name="search_brand">
</section>
</div>
<div id="results">
//ajax-php result gets posted in here
</div>
<div class="button submit_checkboxes_button submit_checkboxes">
<a href""><span>Anwenden</span></a>
</div>
</ul>
</div>
and this is a part of search.php (this is the script that is called by ajax and posts the results):
$result = mysql_query($query);
while($brand = mysql_fetch_array($result)){
echo
'<li><input type="checkbox" id="'.$brand['Brand'].'" value="'.$brand['Brand'].'"'; if(strpos($_SESSION['brand'],''.$brand['Brand'].'') !== false){ echo 'checked="checked"';} echo' />
<label for="'.$brand['Brand'].'" class="checkbox_title">'.$brand['Brand'].'</label></li>';
It seems like the very last two lines (everything between <li></li> tags) does not get "noticed" by the upper js-function. When I put exactly these <li></li> tags into index.php - along with all php parts - however, it works fine.
Please let me know if this is clear.
Does anybody have an idea on how to fix this issue?
Thank you!
ajax call:
$(document).ready(function() {
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search_brand').val();
$('b#search-string').text(query_value);
$.ajax({
type: "POST",
url: "php/search_brand.php",
data: { query: query_value },
cache: false,
success: function(html){
$("div#results").html(html);
}
});
}
[...]