Im trying to use jQuery autocomplete to show my title of news while Im writting on my search form.
But Im having a problem, when Im writing in my search input nothing appears.
I have my header.php file where I have this script to start jQuery autocomplete:
$(function(){
$('.j_autocomplete').autocomplete({
source: "search.php",
});
});
I also have in my header.php a menu with a search form:
<nav id="menu">
<ul>
<li>Home</li>
.....
<li>
<form id="search">
<input name="search" class="j_autocomplete" type="text" placeholder="Search..." />
<button type="submit">Search</button>
</form>
</li>
</ul>
And then I have my source, that is my search.php file, where Im selecting my news title to show on my jQuery autocomplete:
<?php
$search= $_GET['term'];
$readNews = $pdo->prepare("SELECT * from news WHERE title LIKE ? ORDER BY title ASC");
$readNews->bindValue(1, "%$search%", PDO::PARAM_STR);
$readNews->execute();
$resJson = '[';
$first = true;
while($res = $readNews->fetch(PDO::FETCH_ASSOC))
{
if(!$first)
{
$resJson .= ', ';
}
else
{
$first = false;
}
$resJson .= json_encode($res['title']);
}
$resJson .= ']';
echo $resJson;
?>
Everything looks fine for me, and If in my search.php file I put only this code below, I get all this 4 names when I start to writing in my autocomplete,
so it seems that my source is also correct:
<?php
$result = array("Henry","Tom","Terry","Chris");
echo json_encode($result);
?>
Do you see where might be my error?
In autocomplete documentation says that 'term' is querystring key to use, but
I suspect that is something about my $_GET['term'] that is not working correctly, but I already tested with $_REQUEST['term'] and also dont works!
EDIT:
After hours of debugging, and structure changes we finally got it to work.
The problem were a mix of .htaccess rewrites and some small bugs in the previous code.
I'm not sure how to describe everything we did to make it work.
--
Try building your json string more robust.
$data = array();
while($res = $readNews>fetch(PDO::FETCH_ASSOC))
{
$data[] = $res['title'];
}
echo json_encode($data);
EDIT:
To check for undefined index, typ
$search = isset($_GET['term']) ? $_GET['term'] : "";
I'm sympathetic to your plight - I was in the same mess about a year ago, and then I received some great help here on SO.
All of my errors with autocomplete were because I was not presenting a true json file to the autocomplete function. So I learned that for each and every PHP file that you write, run it as a stand-alone, grab the screen output, and test it with jsonlint.
The second thing I was taught is that it may be easier (if you don't have too many variables to read) if you call the entire file with your php first, then present it to the autocomplete function. Once I started with these two steps, I haven't had a major glitch since. Hope it helps you.
JS
$(function(){
$.ajax ({
url: "../php/insurancesinglevarjson.php",
dataType: "json"
})
.done(function (data) {
console.dir(data);
var source = data;
$("#companyname").autocomplete({
source: source});
});
});
Related
Using Joomla version 3.7.5 with Wright template.
I have a module in the left sidebar which has 2 typeahead fields getting data from a local database. The php code is referenced using include_once via the sourcerer plugin.
The typeahead does not work when used in the module. But - if I use the exact same code in an article, the typeahead works correctly.
Do articles and modules load/behave differently? I would appreciate it if someone could explain this behaviour.
The relevant parts of the code follow.
PHP - the first lines of code are:
JHtml::_('script', './templates/js_wright/wright/js/jquery.js');
JHtml::_('script', './styling/bootstrap3-typeahead.min.js');
$document->addStyleSheet("./media/jui/css/bootstrap.css",'text/css',"screen");
HTML - in the form:
<div class="input-prepend span8"><span class="add-on" ><i class="icon-map-marker" ></i></span><input autocomplete="off" style="border-color:#F7980F;" class="typeahead" id="inputIcon" type="text" name="collectionpoint" /></div>
Javascript:
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get('./towns.php', { query: query }, function (data) {
console.log(data);
data = $.parseJSON(data);
return process(data);
});
}
});
and in the towns.php:
$sql = "SELECT Town FROM lkp_towns
WHERE Town LIKE '%".$_GET['query']."%'
LIMIT 5";
$result = $mysqli->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[] = $row['Town'];
}
echo json_encode($json);
Worked it out.
Joomla does not see a module as a seperate page but rather as a nested div of the main page.
Moving the following lines to the main article page on which the module displays solved the problem as the .js needs to be referenced before anything else has loaded:
Removed this from the module and included it in the article:
JHtml::_('script', './templates/js_wright/wright/js/jquery.js');
JHtml::_('script', './styling/bootstrap3-typeahead.min.js');
$document->addStyleSheet("./media/jui/css/bootstrap.css",'text/css',"screen");
I'm making something like stock-price finder, there is data table made up of stock name, code, price.
what I want to do is if user input stock name on index.html, the result will shown at result.php , and If user click stock name, describe more information on view.php. anyway I made up this, the problem is... I think the pagination would be complicated with user, I want to combine pages to one page. not using result.php and view.php, but only index.html.
Like this...
There are some variable moving page to page, so I'm very afraid of how can I merge this pages. user input text, and the code. I don't know how I can control it.
index.html
<form action="./result.php" method="get">
<label>
Search
<input type="text" name="keywords">
<input type="submit" value="Search">
</label>
</form>
result.php
<?php
require_once './require/db.php';
if(isset($_GET['keywords'])){
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("SELECT name,code FROM data2 WHERE name LIKE '%{$keywords}%' ");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results.
</div>
<?php
}
if($query->num_rows) {
while($r = $query->fetch_object()) {
?>
<div class="result">
<a href="./result.php?code=<?php echo $r->code;?>">
<?php echo $r->name; ?></a>
</div>
<br />
<br />
<?php
}
}
?>
view.php
<?php
require_once("./require/file_get_contents_curl.php");
$code = $_GET['code'];
$source = file_get_contents("http://www.nasdaq.com/symbol/$code");
$dom = new DOMDocument();
#$dom->loadHTML();
$stacks = $dom->getElementsByTagName('dl')->item(0)->textContent;
?>
The above code I made up. but I want to merge it. How can I combine 3 documents to 1 document? because of user input 'keywords(index.html->result.php)' and '_GET variable(result.php->view.php)' It's very difficult to me. Please help me.
You can keep your separate files, but instead of displaying the information inside those actual files, you can call them via AJAX (asynchronous HTTP requests) instead. Here's the syntax using jQuery:
index.html
<input type="text" id="keywords">
<button id="search">Search</button>
<div id="result"></div> <!-- The div that will be filled with the result from the AJAX request -->
Javascript
$('#search').click(function(){
$.ajax({
url: "result.php",
method: "POST",
data: {keywords: $('#keywords').val()}
}).success(function(result) {
$('#result').html(result);
});
});
result.php
<?php
require_once './require/db.php';
if(isset($_POST['keywords'])){
$keywords = $db->escape_string($_POST['keywords']);
$query = $db->query("SELECT name,code FROM data2 WHERE name LIKE ' {$keywords}%' ");
echo "Found ".$query->num_rows." results.";
?>
So in the example I made up above you pass in the variable keywords as keywords. This means that inside result.php, you can access the variable keywords via $_POST['keywords'].
So basically, you do the exact same things in result.php and view.php you've done so far, but you return the data to the index.html file instead of just echoing it out in that file. If you want to read more about the AJAX function in jQuery, here's a link: jQuery.ajax().
Hope this helps, please let me know if you wonder something.
This is a very broad question.
So the answer will be very subjective.
If this is your first rodeo, I think its a good time to learn about AJAX.
The basic idea is that you let a javascript request information from the server, and add the response to the page.
AJAX is a complex set of methods, but with modern frameworks like jquery, it's become easy to implement.
See this documentation:
http://www.w3schools.com/jquery/jquery_get_started.asp
and
https://api.jquery.com/jquery.get/
when jquery is added to your page, try this:
$.get( "result.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
if you do not like ajax,
try adding iframes to the index.html, and set the src of the iframe to the php page you want to display.
This will cause them to load once. So you need to refresh them everytime the dropdown changes.
that could be a little tricky: How to refresh an IFrame using Javascript?
I am having a problem with autocomplete that is confusing me a little. I did a search first, I am not the only one having this problem. But everyone seems to use jQuery Autocomplete in their own way, so it didn't really help me.
Anyway, here is the problem. I am building a search function, that is supposed to show a list of users, retrieved from a mysql database. I got that to work. So when I start typing, it immediately shows a list of users. What I want to do next, is to make the results links, that redirect the user to a different page.
Here is findartist.php;
if(isset($_GET['term'])){
$artist = new User();
$return_arr = array();
$results = $artist->findUser($_GET['term']);
foreach($results as $result){
$link = "<a href='profile/index.php?st=" . $result['stagename'] . "'/>" . $result['stagename'] . "</a>";
$return_arr[] = $link;
}
echo json_encode($return_arr);
}
And here is the jQuery;
<script>
$(function() {
//autocomplete
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength: 1
});
});
</script>
The problem is that when I do this, it shows the html code.
So this is what it would look like;
<a href='profile/index.php?st=bob'/>bob</a>
Is there a way to fix this?
This isn't how autocomplete is set-up to work. It's set up to assume what you return is the text you want to display. It can't handle HTML in the way you're asking.
However, that doesn't mean all is lost...
Instead of having findartist return an array of <a> tags, just the artist names.
Then, you write another function, bound to the 'select' event of the autocomplete object that will navigate you to the page you want.
See the documentation for the event in question here: http://api.jqueryui.com/autocomplete/#event-select
For example, findartist.php may change to:
if(isset($_GET['term'])){
$artist = new User();
$return_arr = array();
$results = $artist->findUser($_GET['term']);
foreach($results as $result){
$return_arr[] = $result['stagename'];
}
echo json_encode($return_arr);
}
And your autocomplete may look something like:
<script>
$(function() {
//autocomplete
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength: 1,
onSelect: function (suggestion) {
// event fires when the user selects something from the list.
window.location.href = "profile/index.php?st=" + suggestion;
}
});
});
</script>
Forgive me any mis-matched brackets or syntax error - I'm coding without a workign dev environment. Hopefully it helps anyway.
Try it out, see where you get.
you can work on form submit, it is the best way to redirected to results page
$(document).ready(function(){
$(".artist_input").autocomplete({
source: "/includes/findartist.php",
minLength:1,
select: function( event, ui ) {
$("#name").val(ui.item.label);
$("#form").submit();
}
});
});
I am currently working on a project in which I need to have an autocomplete form call its information from a db file. I have seen many tutorials on jquery autocomplete forms, but I do not know how to call a db file to populate the list.
I am working in PHP. Currently the code represents a simple drop down box that is calling on the db file for population.
<?php
global $wpdb;
$depts = $wpdb->get_results( "SELECT * FROM departments ORDER BY department_name ASC" );
echo '<select>';
foreach($depts as $row) {
echo '<option name="select_dept" value="'.$row->department_id.'">'.$row->department_name.'</option>';
}
echo '</select>';
?>
Any help would be awesome!
I recently have used this library for autocompletion - http://www.devbridge.com/projects/autocomplete/jquery/
So here is brief script based on yours:
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
if ($query) {
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM departments WHERE department_name LIKE '".$query."%' ORDER BY department_name ASC" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->department_name;
$data[] = $row->department_id;
}
$response = array(
'query' => $query,
'suggestions' => $suggestions,
'data' => $data,
);
echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#box').autocomplete({
serviceUrl:'/',
// callback function:
onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
});
});
</script>
</body>
<html>
<?}?>
Please follow this very well written tutorial
http://www.nodstrum.com/2007/09/19/autocompleter/
JQuery UI includes an autocomplete, although you still need to write a PHP script to return the information to be added to the control as its done via AJAX. If you know in PHP how to connect to a database, query it, and return a list of the results - then you will have no problems with this. JQuery makes AJAX extremely simple.
Depending on how complicated your field/data set is - and assuming its not millions upon millions of unindexed records, I would be content to autocomplete from a:
SELECT thing WHERE thing LIKE '".$query."%'
So if you were searching for, say, food... the query "CA" would pull out CArrot and CAbbage and CAuliflower. If you added a % to the beginning of the LIKE, you could get results that contained your query, as opposed to just beginning with it.
The page your user hits would contain the JQuery part which both sends the request and creates the autocomplete effect from the results, and a very simple, separate PHP script which the AJAX request hits would return the potential 'matches'.
Take a look at the Autocomplete demos on JQuery UI
I am having some issues returning data from on page, using jQuery, PHP and MySQL. I would like to show the query results on the index.php page. The results are fetched from the database using getResults.php.
When I manually run the getResults.php?id=123 file, all works fine. In this case i'm seeing the results I would like to. However, when I want to post the 'id' 123 in a submit form on index.php, I don't see any results returned by jQuery / getResults.php. Only thing that changed is the URL: index.php?id=123. However, I'm not seeing any results or an error message...
Any one an idea?
getResults.php file
$search = mysql_real_escape_string( isset ($_POST['id']));
if ($search) {
$friend = mysql_query( " SELECT * FROM reviews WHERE fbuserid = '$search' ORDER BY datumtijd DESC" );
if ( $friend ) {
while ($row = mysql_fetch_array ($friend) ) {
echo "Show some results...";
}
} else {
echo "No matches found";
}
} else {
echo "Query not succesfull";
}
index.php file
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#submit").click(function) {
event.preventDefault();
$.ajax({
url:"getResults.php",
type:"GET",
data: "id="+this.value,
success: function(data) {
$("#results").html(data);
}
});
}
return false;
});
</script>
<div>
<form>
<input type="text" name="id">
<input type="submit" value="submit" id="submit">
</form>
</div>
<div id="results"></div>
EDIT:
Thanks, all for your input. Nevertheless, I'm still not there... As you might notice, I'm not quite experienced with jQuery and PHP. See changes in scripts above. In short:
- I added the false statement if ($query) is not succesfull;
- Changed the $.post method into $.ajax;
- Changed the GET into POST in the PHP file;
Any other suggestions?
You are POSTing data but your script is looking for it in GET.
Edit in response to massive rewrite of the code in the question:
The first argument of $.ajax should be the URL.
You are missing the { from your settings object.
You are using a = instead of : for your type parameter.
You aren't doing anything to stop the normal submission of the form, so the form gets submitted and a new page loaded before the HTTP request sent by the Ajax returns.
In the first line:
$search = mysql_real_escape_string( isset ($_POST['id']));
Try changing $_POST to $_GET:
$search = mysql_real_escape_string( isset ($_GET['id']));
^^^^^
Its much better to use the jQuery ajax method to implement the ajax functionality in the script.
As it is more generalized rather than specific to one METHOD.
Below is the sample code to use the ajax method.
$(document).ready(function()
{
$("#submit").click(function)
{
$.ajax(
type="GET",
url:"getResults.php",
data: "id="+this.value,
success: function(msg)
{
$("#results").html(msg);
}
);
}
});
To check out more examples please refer to the JQUERY API Reference.
J
in if ($query) { is $query !== false ???