Jquery Autocomplete search box results show in HTML format - php

I am having a little issue with the jquery autocoomplete plugin on my site. I have a search box that queries against a database for the usernames of registered users. This works great but one aspect. When the user clicks on the user to finish the search on the query, the results in the input text field show in HTML form which is and .
I want to only show the username they picked in the input box or just directly redirect them straight to the query page.
if this sounds confusing, this is the site and you can search without registering...
http://www.socialpurge.com/search_query.php
Below is some of the php which is the appended code for the search against the database
<?php
$input = $_POST['search'];
include($_SERVER['DOCUMENT_ROOT'] . "/scripts/members_connect.php");
$c_search = mysql_query("SELECT * FROM members WHERE fname LIKE '%$input%' or fullname LIKE '%$input%'");
while($rows = mysql_fetch_assoc($c_search)) {
$data = $rows['fullname'];
$fname = $rows['fname'];
$id = $rows['ID'];
/////// Mechanism to Display Pic. See if they have uploaded a pic or not //////////////////////////
$check_pic = "/members/$id/default.jpg";
$user_pic = print "<img src=\"$check_pic\" width=\"35px\" />"; // forces picture to be 100px wide and no more
print "<a href='profile.php?=&fname=" . $fname ."&user=" . $id . "'>" . $data . "</a>\n";
}
mysql_close($con);
?>
Below is the Javascript function that is calling the above php. This function is appended to the search form
<script>
$().ready(function() {
$("#search").autocomplete("include/user_search.php", {
width: 260,
matchContains: true,
selectFirst: false
});
});
</script>
If you do a quick search on the site, you will see what I am talking about. If anyone has any ideas that would be great. BTW I have tried changing the php a bit and still doesn't work. I am a little familiar with Javascript. I tried changing the source of the autocomplete.js plugin but that didn't work.
Is there a way to use Javascript/Jquery to remove the html tags and just keep text after selection and/or onclick event is triggered?
Please help me
Answer
Ofir Baruch was right, I just had to completely change the function I was using. I was using a seperate function plugin for Jquery. I updated Jquery I had and used the native one that was packaged inside the js file. This is what I did if it helps anyone.
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.2.custom.css" />
<script>
$(document).ready(function() {
$("input#search").autocomplete({
source: 'include/user_search.php',
minLength: 1,
select: function(event, ui) {
var item = ui.item.value.replace(/(<([^>]+)>)/ig,"");
$('#search').val(item);
return false;
}
});
});
</script>
Then in my query file:
<?php
$input = $_REQUEST['term'];
include($_SERVER['DOCUMENT_ROOT'] . "/scripts/members_connect.php");
$c_search = mysql_query("SELECT * FROM members WHERE fname LIKE '%$input%' or fullname LIKE '%$input%'");
$data = array();
if ( $c_search && mysql_num_rows($c_search) )
{
while( $row = mysql_fetch_array($c_search, MYSQL_ASSOC) )
{
$check_pic = "/members/" . $row['ID'] . "/default.jpg";
$data[] = array(
'label' => "<img src='/members/" . $row['ID'] . "/default.jpg' width='35px' /><a href='profile.php?=&fname=" . $row['fname'] . "&user=" . $row['ID'] . "'>" . $row['fullname'] . "</a>"
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
mysql_close($con);
?>
Thanks again

Basicly , the php file should return a JSON string (DATA ONLY),
and the jquery script should handle the "design" of it , appending tags and such (img , a).
Anyway , the auto-complete jquery UI plugin has a select event.
select: function(event, ui) { ... }
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing
Therefore ,
$("#search").autocomplete("include/user_search.php", {
width: 260,
matchContains: true,
selectFirst: false,
select: function(event, ui) {
//use ui.item to manipulate the HTML code and to replace the field's
//value only with the user's name.
}
});
EDIT:
Your php file should return a JSON formated data , as mentioned.
Use an array variable in the next structre:
$results = array(
0 => array('id' => $ROW['id'] , 'name' => $ROW['name'] , 'fullname' => $ROW['full_name']),
....
....
);
use the php function: json_encode and echo it.
In your jquery , do something like:
function(data) {
$.each(data.items, function(i,item){
//use: item.id , item.name , item.full_name
$("#autocomplete-list").append("<img src='dir/to/image/"+item.id+".jpg>"+item.name);
});

Related

Saving form variables onchange with ajax

I'm trying to save form data into $_SESSION variables with ajax, but I can't seem to run the onchange event properly or send the variable.
The form length varies, so I've tried to use dynamic variables.
<script>
function orderValues(boxValue){
$.post("/ajaxConnect.php",{value: $("qty_" + boxValue).val()},
function( result ) {
console.log('value saved');
});
}
</script>
<php
echo "<div id=\"prodBox\">QTY: <input name=\"qty_".rawurldecode($item->LINE)."\" value=\"" . $_SESSION['box_']['qty_'.rawurldecode($item->LINE)] . "\" type=\"number\" onchange=\"orderValues(this.value)\"/></div>";
?>
ajaxConnect:
<?php
session_start();
$_SESSION['box_']['value'] = $_POST["value"];
?>
The end goal is for input values to be saved to $_SESSION['box_']['qty_LINE'] whenever the value is changed.
If I set the $_SESSION value manually I can get it to show, but not through ajax.
Cheers for any help.
It is a better practice to use jquery to do the event bindings instead of using attributes like onchange, and you also need to make sure you get the right values to send to your server, you need both the line name and the value.
So remove the onchange attribute:
<php
echo "<div id=\"prodBox\">QTY: <input name=\"qty_".rawurldecode($item->LINE)."\" value=\"" . $_SESSION['box_']['qty_'.rawurldecode($item->LINE)] . "\" type=\"number\" /></div>";
?>
And use this jquery code:
$(document).ready(function(){
$('#prodBox input').change(function(){
$.post("/ajaxConnect.php",{line: this.name, value: this.value},
function( result ) {
console.log('value saved');
});
});
});
Finally, update your ajaxConnect file:
<?php
session_start();
$line = isset($_POST["line"]) ? $_POST["line"] : '';
$value = isset($_POST["value"]) ? $_POST["value"] : '';
$_SESSION['box_'][$line] = $value;
?>

Refresh one variable every second

I want to refresh two variables named profittext and sumtext which will be refreshed and echoed in the following places every few seconds. I know AJAX is needed to do this but how do i actually make it work ? The only way i found out was to refresh the content of the whole file. is there any way to refresh specific variables? Any answers will be greatly appreciated . Thank you very very much.
<table>
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
?>
<!DOCTYPE html>
<html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">Profit/Loss</th>
</tr>
<tr>
<td style="border:1px solid black;"><?php echo $sumText ;?></td>
</tr>
</table>
</html>
I struggled with the concept of how to structure such code when I first started too. Although it's not specific to your particular variables, here's a quick example for how to update a var through AJAX with jQuery/PHP.
Prologue: If this is something you're going to be doing often, you'll want to learn jQuery, rather than using normal javascript alone. There are lots of great, free, resources on how to learn jQuery. Alternatively, if you're not satisfied with the free tutorials online, this is an excellent book. I'll write the example in jQuery.
Design: Okay, so the way it works is this:
Set a timer in javascript to execute a particular function every X seconds (you DO NOT want to do it every second).
That function makes an AJAX call (with jQuery) to a .PHP file on the server, sending it the data necessary so that the .PHP code knows what to send back.
The .PHP code grabs the data required (e.g., with MySQL) encodes it in a JSON format, and exits.
A promise on the AJAX call is fired and the data sent from PHP is received. Process it as you will.
Repeat from step 2.
If you have any questions about what the code is doing, please ask.
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
MYCODE.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>
You will needd two PHP pages:
- one with HTML and JS, which periodicly makes ajax calls and puts the result to the HTML
- second with json (or even plain text) output of your dynamic data piece
Unfortunately, writing the full code in the answer is not someting that people do at stackoverflow, so just look at small example below, and try to figure out the missing parts.
http://jsfiddle.net/AMEqz/
var xhr = new XMLHttpRequest();
xhr.onload = function(r) {
// your render logic HERE
setTimeout(send, 1000);
}
function send() {
xhr.open("GET", "/", true);
xhr.send();
}
send();
p.s.: keep in mind that each ajax request will mean extra connection to your server, so make sure it can deal with the load ;)
Use a timer : https://developer.mozilla.org/en/docs/DOM/window.setInterval
setInterval(function(){
//update your var here
},1000);

<button> Same Button, Multiple Locations, Different Code

I am writing an application in JQTouch, and am using a big red button
Red
I am using PHP to dynamically build the JQT page with multiple divs. The app is a server management console that gets data from MySQL. My idea is that I use a While loop to make a div for each server returned in the MySQL query, and each div will have a delete server button(the big red button). I have to call the dame bit of code because of the whole dynamic page generating thing. So I was wondering if there was a way I could have the onClick function that I call with the button
Red
know what div the button is in that is calling the function. There will be a button in multiple divs that call the same code, but i have to know WHAT server to delete. Any suggestions?
Here is the full source code.
<html>
<link rel="stylesheet" href="jq_touch/themes/css/jqtouch.css" title="jQTouch">
<script src="jq_touch/src/lib/zepto.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jq_touch/src/jqtouch.min.js" type="text/javascript" charset="utf-8"></script>
<!-- Uncomment the following two lines (and comment out the previous two) to use jQuery instead of Zepto. -->
<!-- <script src="../../src/lib/jquery-1.7.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<!-- <script src="../../src/jqtouch-jquery.min.js" type="application/x-javascript" charset="utf-8"></script> -->
<script src="../../extensions/jqt.themeswitcher.min.js" type="application/x-javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQTouch({
icon: 'jqtouch.png',
icon4: 'jqtouch4.png',
addGlossToIcon: false,
startupScreen: 'jqt_startup.png',
statusBar: 'black-translucent',
themeSelectionSelector: '#jqt #themes ul',
preloadImages: []
});
// Some sample Javascript functions:
$(function(){
// Show a swipe event on swipe test
$('#swipeme').swipe(function(evt, data) {
var details = !data ? '': '<strong>' + data.direction + '/' + data.deltaX +':' + data.deltaY + '</strong>!';
$(this).html('You swiped ' + details );
$(this).parent().after('<li>swiped!</li>')
});
$('#tapme').tap(function(){
$(this).parent().after('<li>tapped!</li>')
});
$('a[target="_blank"]').bind('click', function() {
if (confirm('This link opens in a new window.')) {
return true;
} else {
return false;
}
});
// Page animation callback events
$('#pageevents').
bind('pageAnimationStart', function(e, info){
$(this).find('.info').append('Started animating ' + info.direction + '… And the link ' +
'had this custom data: ' + $(this).data('referrer').data('custom') + '<br>');
}).
bind('pageAnimationEnd', function(e, info){
$(this).find('.info').append('Finished animating ' + info.direction + '.<br><br>');
});
// Page animations end with AJAX callback event, example 1 (load remote HTML only first time)
$('#callback').bind('pageAnimationEnd', function(e, info){
// Make sure the data hasn't already been loaded (we'll set 'loaded' to true a couple lines further down)
if (!$(this).data('loaded')) {
// Append a placeholder in case the remote HTML takes its sweet time making it back
// Then, overwrite the "Loading" placeholder text with the remote HTML
$(this).append($('<div>Loading</div>').load('ajax.html .info', function() {
// Set the 'loaded' var to true so we know not to reload
// the HTML next time the #callback div animation ends
$(this).parent().data('loaded', true);
}));
}
});
// Orientation callback event
$('#jqt').bind('turn', function(e, data){
$('#orient').html('Orientation: ' + data.orientation);
});
});
</script><?php
//Connect
mysql_connect("localhost", "root", "root") or die(mysql_error());
//Make and store queries
mysql_select_db("servermgr") or die(mysql_error());
$result = mysql_query("SELECT * FROM servers")
or die(mysql_error());
//Echo some constant HTML
echo'<div id="serverset">';
echo'<div class="toolbar">';
echo'<h1>Servers Home</h1> ';
echo'</div>';
echo'<ul class="rounded">';
//Begin printing out MYSQL rows (List Items)
while($row = mysql_fetch_array( $result )) {
//$row_friendlyName = $_row['friendly_name']
$friendlyName_noSpaces = str_replace(' ', '_', $row[friendly_name]);
echo'<li class="">'.$row["friendly_name"].'</li>';
}
//Close list
echo'</ul>';
echo '</div>';
//Redo all previous queries to print out the divs
mysql_select_db("servermgr") or die(mysql_error());
$result2 = mysql_query("SELECT * FROM servers")
or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 )) {
$friendlyName_noSpaces2 = str_replace(' ', '_', $row2[friendly_name]);
echo '<div id="'.$friendlyName_noSpaces2.'">';
echo'<div class="toolbar">';
echo'<h1>'.$row2[friendly_name].'</h1> ';
echo 'Back';
echo'</div>';
echo'<ul class="rounded">';
echo '<li>Friendly Name: '.$row2[friendly_name].'</li>';
echo '<li>IP Address: '.$row2[ip].'</li>';
echo '<li>Server Hostname: '.$row2[hostname].'</li>';
echo '<li>MAC Address: '.$row2[MAC].'</li>';
echo'</ul>';
echo'<button href="#" class="redButton">Red</button>';
echo'</div>';
}
//END OF PHP
?>
</body>
</html>
add a data attribute to your "Big Red Button" as follows
Red
and from your handling code retrieve the data value as follows
var server = $(this).attr('data-server');
Then you can do your condition logic.
DevZer0's answer is probably what you want to go with but an alternative approach is to add a class to the containing div like
echo '<div id="'.$friendlyName_noSpaces2.'" class="server">';
Then you can do this in your callback
var server = $(this).closest(".server").attr("id");
to get the id of the containing div.

Download-Page with JQuery request

I have a download page. Members are free to click on their bought songs and the download starts. I wish now that in the same time an Ajax request takes place, which adjusts the count of downloads in the database. The page should then be reloaded to the counter from the database is updated again. If the counter is zero, there is no longer downloading.
Obviously my script does not work. The download happens, but the JQuery-Script will not work. Does someone have a solution?
This is the link to the download-page:
<a href="get-download-files.php?file=xyz.zip"><img class="a_0" src="images/download.png" width="30" height="30" />XYZ-Song/a>
And this is the Java-Script on the same page:
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$.get("zaehler.php?dl_id=1", function(data){
$("#ausgabe").html(data);
});
});
});
</script>
And this is the request-file:
<?php
require_once 'includes/db_login.php';
$dl_id = $_REQUEST['dl_id'];
// counter updaten
$sql = 'UPDATE ' . $tbl_prefix . 'downloads
SET zaehler = zaehler - 1
WHERE dl_id = ' .$dl_id;
mysql_query($sql);
$abfrage = 'SELECT zaehler FROM ' . $tbl_prefix . 'downloads WHERE dl_id=' . $dl_id;
$ergebnis = mysql_query($abfrage);
while ($datensatz = mysql_fetch_array($ergebnis, MYSQL_ASSOC))
{
echo '<h3 style="color:#333;">Dein Download-Stand</h2>';
echo '<br /><br />Du hast noch ' . $datensatz['zaehler'] . ' Downloads zugut.';
}
?>
Im thanking you. Best regards,
Heinz
You don't need Ajax for this. In the script get-download-files.php, update the database before delivering the file to the browser.
Have you tried this?
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>
You can check if your code is executed by adding a alert() inside your function. If the alert fires, the function is executed.
<script>
$(document).ready(function(){
$(".a_0").click(function(){
alert('Function is fired!'); // Debug
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>

Jquery/Ajax and PHP rendering TR

I am scraping sites, and I am doing this one at a time, and then trying to get the results to display AS I get them. I am trying to render one TR at a time, but instead, it does every single one, and then renders ALL the TRs.
Here is the call to javascript:
<body onload="getOffers(companies , {$scraped}, {$isbn13});">
Here is the JS/Jquery function:
function getOffers($company_ids, $scraped, $isbn)
{
if($scraped)
{
$.ajaxSetup({cache: false});
for(var $id in $company_ids)
{
$.ajax({
url: "../get_offer.php",
data: "id=" + $company_ids[$id] + "&isbn=" + $isbn + "&code=" + $id,
dataType: "html",
success: function(data) {
$("#results tbody:last").append(data);
}
});
}
}
else
{
return true;
}
}
And here is the PHP page:
<?php
require_once 'scrape.php';
require_once 'include.php';
$id = requestValue('id');
$isbn = requestValue('isbn');
$code = requestValue('code');
$page = curlMultiRequest(isbn10($isbn), $id);
$offer = getOffer($code, $page[$code], isbn10($isbn));
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
?>
I tried returning the sting I am printing, but that didn't even work. How can I make it print each table row to the screen as the data is retrieved?
EDIT: so I tried adding this:
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
ob_flush();
flush();
To the PHP and it didn't work. I don't understand, if I throw an alert, it happens on the fly for every ID, but the html rendering does not.
It may have magically fixed itself because your browser was caching some of the javascript. You should use some developer tools to manually flush the cache of resources for the host you are testing on to avoid old code being subtly used ....

Categories