jQuery UI autocomplete gets has suggestions but doesn't display them - php

I have a jQuery autocomplete script in my page, and if I type in the field it works on, and as requested after 3 characters, the drop containing the expected number of suggestions pops down...sort of...as there is no text in the drop down.
If I mouse over the drop down as though I were selecting one of the suggestions, a narrow bar shows a highlight for each row where a suggestion would be, but selection of one of the empty highlights empties the field. This is not surprising. I don't really understand the handling of the return data. I have seen very simple and complex code in autocomplete examples in other posts in these forums, but using the ones I thought I understood has usually broken it to the point where I don't get the drop down at all. Thus I'm unashamedly looking for someone to provide me with the code that works so I can pick it apart and work out how it works.
My basic JS code is:
$("#tf_txt_CLIENTNAME").autocomplete({
source: "search.php",
minLength: 3,//search after three characters
dataType: 'json',
select: function(event,ui){
//do domething
}
It's the do something area I just can't get right. As I said, I've tried too many variations of code in that space to mention here, and all of them broke it completely.
search.php produces the following JSON output for input of 'bra':
[{"txt_CLIENTNAME":"Braedon"},{"txt_CLIENTNAME":"Bradly"}]
from the following PHP source (borrowed and modified from another web source):
<?php
require_once 'includes/dbiconnect.php';
require_once 'includes/sqlfunctions.php';
$term = trim(strip_tags(addslashes($_GET['term']))); //retrieve the search term that autocomplete sends
$qstring = "SELECT `txt_CLIENTNAME` FROM `tbl_client_details` WHERE `txt_CLIENTNAME` LIKE '%".$term."%'";
$result = mysqli_query($db_link,$qstring); //query the database for entries containing the term
while ($row = mysqli_fetch_assoc($result)) {//loop through the retrieved values
$row['txt_CLIENTNAME']=htmlentities(stripslashes($row['txt_CLIENTNAME']));
$row_set[] = $row; //build an array
}
echo json_encode($row_set); //format the array into json data
?>
I simply would like it to display what it finds and plonk the one I select into the value of the text field. I can then update the other fields I want to populate (company, phone # & e-mail) using $.POST triggered by the onchange event for that field (I'm sure there are better ways to do that, but I understand how to do that for the moment).
I'm using jQuery 1.7.2 and jQuery UI 1.8.22. I have the latest jquery toolbox loading as well without the tabs component, but removing it has made no difference.
Thanks in advance,
Braedon

As per Jquery UI guide,
your JSON needs to contain label or value (or both)
You need to change your json as below
while ($row = mysqli_fetch_assoc($result)) {//loop through the retrieved values
$row['txt_CLIENTNAME']=htmlentities(stripslashes($row['txt_CLIENTNAME']));
$row_set[] = array('label'=>'txt_CLIENTNAME','value'=>$row['txt_CLIENTNAME']); //build an array
}

Related

Change the value of second select on first select

I'm sorry I haven't included "my attempt" as such with this one, I'm useless with jquery so need some advice!!
I would like to change the value of a second selctor based on the results of the first.
I have a database of builders and regions with the headers builder_name and builder_region. The list ends up looking like this ...
builder_1 region_1
builder_1 region_2
builder_2 region_1
builder_3 region_1
builder_3 region_2
builder_3 region_3
(You get the idea)
I'm using the following in the form I've built to get a list of the builders for the first select box ...
echo '<select class= "ml-select" name="gen_builder">';
echo '<option value=" ">Select Builder</option>';
while($row = mysql_fetch_array($rsBUILDER)) {
if($linebreak !== $row['builder_name']) {
echo '<option value="'.$row['builder_name'].'">'.$row['builder_name'].'</option>';
}
else {echo "";}
$linebreak = $row['builder_name'];
}
echo '</select>';
The $linebreak is to get rid of the duplicate builder names from the list, which works a treat.
What I would like to achieve is a second selector that selects the regions available, dependant upon the builder that has been selected in the first option. I hope this makes sense????
The second query needs to look at the builder selected in the first selector and filter out just the regions that are in rows with the builder name form selector one.
Please do say if you need further information, I'm not great at explaining myself.
As you said you don't have experience with jQuery or Ajax, I'll post my answer with as many comments as possible. I will assume that you have two select dropdowns in your page.
The first one contains the builders, so it will have id="builders".
The second one contains the regions, so it will have id="regions".
From what I understand, the first select will be exactly the one you posted in your question, generated server-side (by PHP). I only ask that you please make a slight change on it, making each option value be equal to the builder's database ID, and not its name (unless the builder's primary key is their name, and not an ID). This will make no difference for the final user but will be important for our jQuery solution. The second one will be empty, as the idea is to fill it dynamically with the regions related to the builder selected in the first dropdown.
Now let's get to the jQuery code:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
//The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
$('#builders').change(function() {
//$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
var currentValue = $(this).val();
//Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions);
$.get("get_regions.php", {'builder_id': currentValue}, function(data) {
//Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
var regions = $.parseJSON(data);
//Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
$('#regions').empty();
//Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
for (var i = 0; i < regions.length; i++) {
var regionOption = '<option value="'+regions[i]['region_name']+'">';
regionOption += regions[i]['region_name'];
regionOption += '</option>';
$('#regions').append(regionOption);
}
});
});
});
Despite any syntax errors (can't test the code from here) this should do the trick. Hope the comments were clear enough for you to understand how things work in jQuery.

jquery autosuggest add heading before items

I am using jquery autosuggest and would like to add a default heading just before all the items appear. For example when the user starts his search the first drop down item would say 'We Suggest:' followed by the list of items. Here is what I currently have
$term=$_GET["term"];
$query=mysql_query("SELECT DISTINCT region FROM business where region like '$term%' limit 10 ");
$json=array();
while($region=mysql_fetch_array($query)){
$json[]=array(
'value'=> $region["region"],
'label'=>$region["region"]
);
}
echo json_encode($json);
I have a reasonable understanding of php and jquery but not json
Thanks for any help
NEW ANSWER:
I may have misread your question before. Perhaps you are just asking for this:
$( "#mylist" ).autocomplete({
source: myjsonarray,
open: function( event, ui ) {
$('.ui-autocomplete').find('li:first').prepend("<div>We Suggest:</div>")
}
});
Access the "open" event, add a div before the first list item.
OLD ANSWER:
//make an empty container
$myresults=array();
//manually create your first item
$myfirstitem=array("value"=>"We suggest","label"=>"We suggest")
//put your first item in the container
array_push($myresults,$myfirstitem);
// fetch your data
while $result=mysql_query("SELECT phrase from mytable"){
//put each item in the container
array_push($myresults,array(
"value"=>$result,
"label"=>$result
));
}
//$myresults is now full of phrases.
///Uncomment this to check it if you want.
//var_dump($myresults);
//encode and echo your result
echo json_encode($myresults);
The above code illustrates one way to do what you want to do. With that said, I'd probably not put "We Suggest" as an actual option... if you're presenting a list of baseball cards, it wouldn't make sense for the user to choose "we suggest" as their favorite baseball card...
Also, don't let json bother you- it's just a "notation". This example is very simple- think of it and use it as any other array.
You can also do this more efficiently- you don't need to return a label and a value... but that's another conversation.
Also, it's important that you do not use mysql_* functions. Look into mysqli and pdo.
Good luck, I hope that helped.

jQuery context menu filled with php content based on selection

When a user selects a word in a text on my website (PHP), and then right clicks, i want a jQuery context menu to come up, this can be done by using one of the already existing jQuery context menu plugins.
But besides the options like copy / paste / cut, etc. I also want something to be done with the selected word using PHP. Which, i think, is a little harder.
For example using this script:
$selection = //the selected word or text
$target = //fetch from MYSQL database
$output = array();
while ($row = //fetch $target) {
If ($selection == $row->input) { array_push($output,$row->output); }
}
echo '//menu '.print_r($output).''; // of course not print_r! Just for the example's sake.
Databse example:
(Sorry for the oversized image)
Ok so selecting the word 'lazy' in the example text, and then right clicking, the jQuery box should pop up showing the results from the database extracted by PHP.
Example:
Ok, so i know you can't just combine javascript with PHP and it can only be parsed, but i thought loading an iframe withing the menu, which does the database extraction would do the job by using javascript to set the iframe src containing the selected word in the url.
However, iFrames are not really a nice way to solve this.
The question: How can i do this effectively? Execute this script on right-click and show the database-related content in the menu?
I would need to know the plugin you're using to give you some code examples but, general, I would go about this like this:
There has to be a click handler on the items in the jQuery context menu. Use it to submit an AJAX request to the server when the "selection" term is clicked.
Make sure to give the user some feedback (a loader or spinner)
Put the results into an array server-side.
JSON encode the array and send it as the response (e.g. echo json_encode($output)
JSON.parse(response) on client-side and you now have a JS object with the results
Put those results in the context menu (again, how depends on the plugin you're using)
AJAX is a great way to do what you want.
Here is a simple AJAX example. Note that in the 2nd .PHP file, that is where you put your database lookup etc.
Whatever you echo from the 2nd script is received by the calling javascript (first script again) and can be inserted into your context menu on-the-fly. Here is another example with a very detailed, step-by-step explanation of the process at the bottom of the answer.
I think you have to use Ajax to get JSON from a PHP file, which you would process on the actual page.
I you create a PHP file called test.php, with the following in it:
<?php
echo json_encode(array('time' => time(), 'hour', date('H')));
?>
Then the Javascript:
<script>
$('#curr_menu_entry').click(function() {
$.getJSON('test.php', function(data) {
$.each(data, function(key, val) {
$('#curr_menu_entry').append('<li id="' + key + '">' + val + '</li>');
});
});
});
</script>
Would that work?

How to use php to feed data to jQuery autocomplete?

This is a continuation of an earlier post. Unfortunately, The solutions posted didn't work and my follow up questions weren't addressed. Just in case this is because my generous respondents didn't notice I had replied, I'm reposting my problem.
I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
After implementing the suggestions of one of my respondents, the code now looks like this:
<script>
$(document).ready(function(){
<?php global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?>
var data = new Array(); <?php foreach($entries as $value){ ?>
data.push(unescape('<?php echo rawurlencode($value); ?>');
<?php } ?>
$("#field_name-of-the-school").autocomplete(data); })
</script>
// 37 is the field id I want to pull from in the database,
// and #field_name-of-the-school is the css id
// for the text field in the form where a user can enter the name of a school.
// the data for that field is stored in the db under field id 37.
// other fields, like school id, have their own field ids.
My respondent suggested adding the data.push(unescape('<?php echo rawurlencode($value); ?>'); bit. Unfortunately, it's still not working.
BTW, the code is in the body of page.php, a template which wordpress uses to generate static pages (the form is on one of these).
I would seriously, seriously appreciate any and all help with this. If this approach is a dead end (on the earlier posts, there were two other answers that were over my head,) I would be more than willing to learn some new tricks (though it would really help to be pointed to a relevant learning resource.)
Thanks in advance.
I would jsut use json_encode and simplify it:
<script>
$(document).ready(function(){
<?php global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?>
var data = <?php echo json_encode($entries); ?>;
$("#field_name-of-the-school").autocomplete({source: data});
}); // note you were missing a semicolon at the end of this, which i added
</script>
Of course using the above may not be waht you want if $entries is an associative array instead of a numeric indexed one. If thats the case you can do json_encode(array_values($entries));
You have to use
$("#field_name-of-the-school").autocomplete({ source : data });
as shown in the Autocomplete documentation example. Also you might think
about using JSON.

jQuery: Using autocomplete to add values to two fields instead of one

I want to use the autocomplete plugin for jQuery to populate not one, but two fields when selecting one of the autocomplete values - the name of a band is entered in the #band input field, but the band url (if exists) should also automatically be added to the #url input field when selecting the band name.
Right now I simply have an un-pretty list in an external php file from which the autocompleter takes it's values:
$bands_sql = "SELECT bands.name, bands.url
FROM bands
ORDER BY name";
$bands_result = mysql_query($bands_sql) or print (mysql_error());
while ($bands_row = mysql_fetch_array($bands_result)) {
$band_name = $bands_row['name'];
$band_url = $bands_row['url'];
echo $band_name."\n"; #needs to be replaced with an array that holds name and url
}
My autocomplete function looks very basic atm, but as I'm an absolute beginner when it comes to jQuery (and also clueless when it comes to PHP arrays), I have no idea how to tell it to populate two fields and not one.
$(document).ready(function() {
$("#band").autocomplete('/autocomplete-bands.php');
});
Is that even possible?!
sure check use result hadler so you can then do what you want once a choice has been made
I don't know about the particular plug-in you are using, but I would use the autocomplete widget for jQuery UI instead of a third party plug-in.
Here is an example of what you are looking for:
$("#band").autocomplete('/autocomplete-bands.php').result(function(event, data, formatted) {
if (data)
$('#url').(data['url']);
else {
// no data returned from autocomplete URL
}
});
I don't know much about php, but whatever the format of your data that is returned should be put where the data['url'] is currently in order to populate the #url input.

Categories