jQuery UI autocomplete showing html code - php

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

Related

Change HREF link depending on elements "value" in jquery

I have the following PHP that returns records from a my MYSQL table. These records are displayed as LINKS. See code below...
<div class="slide1" id="u1026">
<?php while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental.php?id={$row['client_name']}\"></a>";
}?>
</div>
What I would like, is for the HREF link to change to
\"brochures\items-rental-layout2.php?id={$row['client_name']}\
If VALUE contains the text "layout2". I know that I can change HREF using jquery code
$(document).ready(function () {
$("#event").attr("href", "http://the.new.url")
});
I'm just not sure how to do that depending if the VALUE contains text "layout2". Any help is much appreciated. Thanks
You can just do it straight in the PHP code:
while ($row = mysql_fetch_array($query_rental)) {
$layoutFlag = $row['layout'] == 'layout2' ? '-layout2' : '';
echo "<a class='fancybox fancybox.iframe' id='rental' value=\"{$row['layout']}\" href=\"brochures\items-rental{$layoutFlag}.php?id={$row['client_name']}\"></a>";
}
You could also do it with Javascript:
$(function () {
// I'm assuming you are going to turn it into a rental class, otherwise change the selector to whatever.
$("a.rental").each(function() {
var rentalItem = $(this);
if (rentalItem.attr('value') === 'layout2') {
// You can choose what to replace, as long as you know it will replace EXACTLY what you want it to. I'm just going with Regex's ^ (start-of-line) operator to make sure that what we are replacing is at the start of the line...
rentalItem.attr('href', rentalItem.attr('href').replace(/^brochures\\items\-rental/, 'brochures\\items-rental-layout2'));
});
});
As you can see, just doing it in PHP is so much easier.
Also as a side note, you are creating multiple elements with the same id. Maybe you meant class='fancybox fancybox.iframe rental'?
And as a second side note, I suggest using the data- prefix for holding custom data. In layout's case, use data-layout='layout-whatever'. You can then use .attr('data-layout') to get the layout attribute (it's easier to understand what that code is doing too!).
You can either run the IF statement on the PHP loop
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
Or by jQuery
$( "a.fancybox" ).each(function( index ) {
if($(this).val() == "layout2") {
oldHref = $(this).attr('href');
newHref = oldHref.replace('items-rental.php', 'items-rental-layout2.php')
$(this).attr('href', newHref);
}
});
all your links have the same ID which can cause some issues when you wuold want to work with them with jQuery.
If you have more a tags with the fancybox class, try adding a unique class to these tags and update the each loop

adding jquery a href class selector after PHP entry has been called to DOM dynamically

I've been trying to come up with a solution for this problem. I thought .live() would help but it isn't used in jquery 1.9.1
I have this function - the gist of which is this:
while($row = $result->fetch_assoc()) {
$currentID = $row['UserID'];
$query2="SELECT FirstName, LastName, UserID FROM Users WHERE UserID = $currentID";
$result2 = $mysqli->query($query2);
$row1 = $result2->fetch_assoc();
echo '<div class="commentEntry">';
echo "<h5><a href='user.php?User=".$row1['UserID']."'>".$row1['FirstName']." ".$row1['LastName']."</a></h5>";
echo "<p>".$row['Content']."</p>";
echo "<p class='agree'>Agree</p>";
echo "</div>";
}
This function works, it isn't the issue.
So essentially with jquery I want to get hold of all dynamically added instances of a.agreeWith.
To test, I am using this:
$(document).ready(function() {
$('a.agreeWith').click(function(event) {
event.preventDefault();
alert("test");
var agree = $(this).id;
var data = 'Agree=' + agree.val();
});
});
Now what I find isn't happening, is that the alert never appears. The a href link still triggers and so clearly there is no call.
I have tested it simply by writing whatever into the page, and it works, the alert appears.
So clearly there is an issue with dynamically loaded information and trying to apply jquery to it.
The question is. How do I get around this?
Thanks for your help.
This should work for you at least to get your alert working. Not sure what your trying to do after....
$(document).ready(function() {
$(document.body).on('click', 'a.agreeWith', function(event) {
event.preventDefault();
alert("test");
var agree = $(this).id;
var data = 'Agree=' + agree.val();
});
});

Database filtering with javascript and AJAX

I've been reading and watching a lot of tutorials about javascript, jquery and AJAX but I can't seem to understand how to make a 'filter' like these guys from unlim500 have.
Their script allows you to just click on a brand and then the table gets filtered and refreshed (without reloading the page).
Live example on this page, click on Все марки:
http://www.unlim500.ru/results/
Can anyone lead me into the right direction?
How can I make such a filter?
index.php =
<a id="bugatti_link" href="#" database_id="Bugatti">Bugatti</a>
<script>
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"brand": vehicle_database_id};
$.getJSON("query2.php", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
</script>
query2.php =
<?php
$host = "xx";
$user = "xx";
$db = "xx";
$pass = "xx";
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$rows = array();
if(isset($_GET['brand'])) {
$stmt = $pdo->prepare("SELECT brand FROM cars WHERE brand = ? ");
$stmt->execute(array($_GET['brand']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
The actual page you linked uses an anchor to create a link to some javascript. The way I have done this in the past (and imo a simpler way) is to make a link without href pointing to the same page (to avoid reload), and attach a click event to the link which will trigger your ajax call.
eg - HTML - the link to click
<a id="bugatti_link" href="#" database_id="2">Bugatti</a>
then in jquery
$("#bugatti_link").click(load_ajax);
function load_ajax(e) {
var link = $(e.target);
var vehicle_database_id = link.attr("database_id");
var ajax_params = {"id": vehicle_database_id};
$.getJSON("the/url/to/the/database/view", ajax_params, success_handler)
}
function success_handler(data) {
//data variable contains whatever data the server returned from the database.
//Do some manipulation of the html document here. No page refresh will happen.
}
On the server you'll receive a GET request to the/url/to/the/database/view which will have a parameter called "id" with the value of "2" so you can fetch vehicle at row 2 and return whatever data you wanted from that vehicle.
Hopefully that gives some insight into how to turn a regular link into an ajax loader, which can be used to update the page without reloading it.
Some useful links about this sort of thing:
jQuery ajax calls
and more useful for this sort of usage, jQuery getJSON
You can use a jquery plugin for the sorting functionality. One of which is the tablesorter plugin
All you have to do is to download jquery and tablesorter.js then include them in your page. The code below assumes that you have jquery and tablesorter on the same folder where you have the file that you're running:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="tablesorter.js"></script>
Add an id to your table:
<table id="myTable">
Then use the tablesorter on document load:
<script>
$(function(){
$("#myTable").tablesorter();
});
</script>

jQuery Autocomplete Mysql PHP

Hi could some one please take a look at this and let me know where I'm going wrong. I am trying to get jQuery UI autocomplete to work. this is my code:
This is search.php
include "db_connect.php";
$search = $_GET['term'];
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
print json_encode($rows);
?>
this is my javascript inline script
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./search.php",
minLength: 3
});
});
</script>
and this is the 'auto' div
<div id="searchTxtFieldDiv">
<p><input type="text" id="auto" /></p>
</div>
When I look at the call using firebug I see that search.php is returning
[{"Title":"Sin City"}]
jQuery is just displaying UNDEFINED
any ideas??
Have a look at jquery ui autocomplete documentation. The JSON you are returning does not match what the autocomplete is looking for. The object you return must have properties named label or value (or both).
You can try the following options:
Option 1: Change returned JSON
Change the JSON being returned to include the label/value properties such as:
[{"label":"Sin City"}]
From the examples it also seems to use the id property. I believe the above is the minimum requirement for the autocomplete to display a list of values. I think you can also return an array of strings and it will render it in exactly the same way as the above.
[ "Sin City", "Etc" ]
Option 2 : Change private _render function
Change the private _renderItem function for the autocomplete to use your custom properties as shown in this autocomplete example (untested):
$( "#project" ).autocomplete({
source: "./search.php",
minLength: 3
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.Title )
.appendTo( ul );
};
This is a bit more flexible but much uglier imho.
#Shaun
Thanks mate, sometimes you just need someone to point out the obvious.
The way I finally got it to work was
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['Title'].'"}';
}
$json .= ']';
echo $json;
atleast run mysql_real_escape_string() on $search before jamming it into a SQL Query.
The source: bit in your javascript is probably messing it up. You should remove the . if 'search.php' is at the 'top' of the documentroot directory.
Firebug will probably help you take a peak at the communication as well.
I was going to say this, always sanitize user inputs.
It's hard to say since I never used jQuery autocomplete but I think you should target the value of "#auto". Something like this: $('#auto').val().autocomplet

How do I use php to feed data to jQuery autocomplete?

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.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...

Categories