I trying to fine tune an autocomplete text box. What I have here works (albeit a bit messy). But I would like to display the values available when clicking into the text box, then filter down as you type. Also, is there a simpler way to code this?
<?php
session_start();
if(isset($_SESSION['myusername'])) {
$User = $_SESSION['myusername'];}
$db1 = realpath('C:\AccessBackEnds\CETracker\CETracker.accdb');
$conn1 = odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$db1",'','') or die ("Unable to connect to server");
?>
<link rel="stylesheet" href="../datepicker/jquery-ui2.css" />
<script src="../datepicker/jquery-1.9.1.js"></script>
<script src="../datepicker/jquery-ui.js"></script>
<script>
$(function() {
var availableTasks = [
<?php
$info0 = "SELECT DISTINCT TaskName FROM CT:MyTasks WHERE UserName = '$User'";
$rs0=odbc_exec($conn1,$info0);
while($row = odbc_fetch_array($rs0)) {
$TaskName = "" . $row['TaskName'] . "";
echo '"';
echo $TaskName;
echo '", ';
}
?>""];
$( "#Tasks" ).autocomplete({
source: availableTasks
});
});
</script>
<div class="ui-widget">
<label for="Tasks">Tasks: </label>
<input name="tasks" id="Tasks" style="width: 400px">
</div>
I think you could enhance the readibility of your script if your split it in two files:
A frontend file, that one has HTML and JS code
A backend file, which has PHP code that generate JSON code.
The frontend file can call the backend file by a json invocation, take into account that the "Autocomplete" widget of jQuery UI has this functionlity built-in. Have a look here in "Remote JSONP Source".
Also PHP can easily generate JSON data by json_encode function.
Related
I am creating a page display a list of products and want to be able to filter by category, have pages, a item per page limit and a sort order
on the store page I do a database call to generate all categories and put them in a sidebar.
Then on click/change serialize all the date on the form using $('#form').serialize() then pass it to request_handler.php which will return the correct data.
The problem is, is that because it is all POST data there is no URL reference so people will not be able to link to the results from their choice similar to -
http://www.asos.com/Men/Shirts/Cat/pgecategory.aspx?cid=3602#state=Rf989%3D6200%2C4885&parentID=Rf989&pge=0&pgeSize=36&sort=-1
Also you will not be able to go back and forth because it is all AJAX. I may be able to solve this with history JS but im not sure how to use a url to get the desired results.
<?php
// Database config file, db login settings
require_once '../inc/dbconfig.php';
try {
// connect to database;
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt_all_results = $conn->prepare('SELECT * FROM films ORDER BY category ASC');
$stmt_all_results->execute();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<form id="store">
<ul>
<?php
$category = null;
while($r = $stmt_all_results->fetch()){
if ($category != $r['category']) {
$category = $r['category'];
echo '<li>
<label for="cat-' . $category . '">
<input type="checkbox" name="cat[]" id="cat-'. $category .'" value="' . $category . '">'
. $category .
'</label>
</li>';
}
}
?>
</ul>
</form>
<div class="result"></div>
<?php
// close try
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<!-- LOAD JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function get_data(dat){
$.post( "request_handler.php", dat)
.done(function( data ) {
$( ".result" ).html( data );
});
}
$('li').change(function(){
var dat = $('#store').serialize();
get_data(dat);
})
</script>
Request Handler Script
<?php
// Database config file
require_once '../inc/dbconfig.php';
$category =$_POST['cat'];
foreach ($category as $i){
$options[] = "category='" . $i ."'";
}
$sql = "SELECT * FROM databse";
if (count($options)){
$sql .= " WHERE " . implode(' OR ', $options);
}
try {
// connect to database;
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt_all_results = $conn->prepare($sql);
$stmt_all_results->execute();
# default
$get_pages = isset($_GET['page']) ? $_GET['page'] : 1;
while($row = $stmt_all_results->fetch()) {
$product_title = $row['title'];
$product_image = $row['image_src'];
$product_category = $row['category'];
$product_id = $row['id'];
?>
<ul>
<li>
<img src="<?php echo $product_image; ?>">
<h4><?php echo $product_title; ?></h4>
<p><?php echo $product_category; ?></h4>
More Info
</li>
</ul>
<?php
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
-if this post is confusing don't attack it just suggest rewording as i have been searching all day to solve this issue - thanks
Mixing php with html/js/css nowadays is suggested bad practice. Some sort of framework and templating (separation of logic and data representation) is must have.
Interactive clientside applications for data manipulation should be built using proper instruments, like angular.js, ember.js, whatever. If you try to do that in raw JavaScript, or even using jQuery, you will surely suffer a lot in both development and support of that application.
If you don't want to confuse yourself with clientside frameworks and prefer oldschool way, I'd recommend you take a look at jQuery plugin called jqGrid. It has sorting, filtering, pagination, etc. built in, but you will have to do much work on the serverside anyway.
Also if you want sorting/filtering/page number parameters to be passed in the URL, you'll have to initialize grid properly, set those parameters using grid API, and reload it.
And I'd strongly recommend you try some sort of templating engine anyway. That will make your code much more clear and consistent.
I am trying to insert a jQuery function into a Wordpress page that connects to a MySQL database that returns a large list of items for an autocomplete text input in a form. It's not working.
Here is my function in it's own .js file in a js folder I created within the file structure of the theme I'm using:
jQuery(document).ready(function($) {
$(
var availableTags = [
<?php
$dbh=mysql_connect ("localhost", "db_name", "db_name") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("db_name") or ("Database not found");
$query = "SELECT col FROM table";
$result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "\"". $row['col']."\", ";
}
// $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
mysql_close($connect);
?>
];
$( "#id" ).autocomplete({
source: availableTags
});
)});
These are the external links:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
This is what I've inserted in my theme's functions.php file:
add_action( 'wp_enqueue_scripts', 'add_my_script' , 11 );
function add_my_script() {
wp_enqueue_script(
'function_name',
get_template_directory_uri() . '/js/function_name.js',
array('jquery'),
'1.0',
true
);
}
You can not run php code into javascript file. So what you should do:
You should use ajax, learn at first how to use ajax in wordpress. Reference example: http://www.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/
Wordpress already has database connection, you shouldn't reconnect. Just you will do quesry only. This is the class reference how will query and other things query related in wordpress : http://codex.wordpress.org/Class_Reference/wpdb
You have mentioned that autocomplete in input filed, so you should use onkeyup, onkeypress similar event in to the js snippet.
However, you should learn overall things separately and then go to execute as your expectation.
global $wpdb;
$results = $wpdb->get_results( "SELECT col FROM table");
foreach ($results as $tableResult)
{
echo $tableResult->col;
}
I have phpbb forum and I wanted to add a field in the registration page...the modification was to enable the user to choose their role .. for example to be a moderator .. or to be a normal member or .. I am actually making the forum a bit private and I am grouping users in groups so they have a restricted access to some forums. Anyways I have the html template file and I want to get the dropdown menu list from a php file code
here is my code of the php
<?php
include '/blah/config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpasswd);
if(!$con)
{
die("Couldn't Connect: ".mysql.error());
}
mysql_select_db($dbname, $con);
$result = mysql_query("SELECT group_name FROM phpbb_groups");
$array = array();
while($row = mysql_fetch_array($result))
{
$array[] = $row[0];
}
mysql_close($con);
foreach( $array as $group_name)
{
echo $group_name."</br>"; // I want to put this value in the dropdown list in the html file
}
?>
here is the part of the html code that I want to edit
<dt><label>GroupID:</label></dt>
<dd><select name="group_id" id="group_id"" tabindex="7" class="autowidth">I want to get the data from php in here</select></dd>
PS: the template file is HTML file and can't be renamed to php
Okay, sorry about the last answer, didnt read your PS there...
Here's a jQuery solution, uses JSON as an output from your PHP file then an asynchronous request to fill in the dropdown.
PHP Code
// The rest of your code, then output your $array this way
header("Content-type: application/json");
$array = array("banana", "apple", "eggroll");
echo json_encode($array);
die;
Your HTML (example)
Make sure you add jquery into your HEAD if you dont already have it.
<dt><label>GroupID:</label></dt>
<dd><select name="group_id" id="group_id"" tabindex="7" class="autowidth"></select></dd>
<script>
$(document).ready(function() {
$.get('sefesf.php', {"q":"1"}, function(data) {
if(data.length > 0)
{
for(var i = 0; i < data.length; i ++)
{
$('select#group_id').append('<option>' + data[i] + '</option>');
}
}
});
});
</script>
Be sure to change sefesf.php to your php file with the json output and {"q":"1"} to {} if you dont need any GET parameters sent.
How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.
I have a problem with some JSON data. I don't know how to take some data generated in PHP and turn that into something that I can use in my jQuery script. The functionality I need is this: I need to be able to click on images on the page, and depending on the selected element, I need to show results from my DB.
Here's the HTML page that I've got:
<html>
<head>
<title>pippo</title>
<script><!-- Link to the JS snippet below --></script>
</head>
<body>
Contact List:
<ul>
<li><a href="#">
<img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
</a></li>
<li><a href="#">
<img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
</a></li>
<li><a href="#">
<img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
</a></li>
</ul>
</body>
</html>
Here's PHP code being called:
<?php
include('../dll/config.php');
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$_POST['name'] = ucfirst($row['name']);
$_POST['tel'] = $row['telephone'];
$_POST['companymail'] = $row['companymail'];
$_POST['mail'] = $row['email'];
$_POST['fbid'] = $row['facebook'];
}
?>
Here's the Ajax JavaScript code I'm using:
<script type="text/javascript">
function change(user) {
$.ajax({
type: "POST",
url: "chgcontact.php",
data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
success: function(name,tel,companymail,mail,fbid){
alert(name);
}
});
return "";
}
</script>
Someone told me that this JS snippet would do what I want:
$.getJSON('chgcontact.php', function(user) {
var items = [name,surname,tel,companymail,email,facebook];
$.each(user, function(surname) {
items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
});
/*
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
*/
});
But it is not clear to me - I don't understand how I need to use it or where I should include it in my code.
You will have to create a proper JSON string in your PHP script, and then echo that string at the end of the script.
A simple example:
$person = new stdClass;
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
$person->name = ucfirst($row['name']);
$person->tel = $row['telephone'];
$person->companymail = $row['companymail'];
$person->mail = $row['email'];
$person->fbid = $row['facebook'];
}
echo json_encode($person);
There are several problems with your code I have tried to explain via the corrected and commented code here:
HTML & JavaScript
<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
$.ajax({
type: "POST",
url: "chgcontact.php",
// use javascript object instead of `get` string to represent data
data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
success: function(data){
// removed name,tel,companymail,mail,fbid
alert(JSON.parse(data));
}
});
return "";
}
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</li>
<li><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</li>
<li><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</li>
</ul>
</body>
</html>
PHP
<?php
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )){
// create data object
$data = new stdClass();
// add values to data object
$data->name = ucfirst($row['name']);
$data->tel = $row['telephone'];
$data->companymail = $row['companymail'];
$data->mail = $row['email'];
$data->fbid = $row['facebook'];
// send header to ensure correct mime type
header("content-type: text/json");
// echo the json encoded data
echo json_encode($data);
}
?>
All code is untested, but you should be able to see what I have done at each step. Good luck.
And to expand on Brian Driscoll's answer. You will need to use the user.name format to access the name field from the returned $.getJSON("blah", function(user){});
so...
items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);
In this format that you have created it will just push a long ugly looking string so you might want to spend some time making it look better. Good luck!
JSON that is POSTed to a PHP page generally isn't in the $_POST variable, rather it is in $HTTP_RAW_POST_DATA.