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;
}
Related
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.
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.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript echo’d by PHP doesn’t run
In the following code I am parsing values from a php table into a javascript function, however I am getting an Uncaught ReferenceError: "the php text" is not defined (anonymous function)
<html>
<script type="text/javascript">
function draw(name ) {
alert(name);
}
</script>
<body>
<canvas id="mycanvas" width=800 height=400></canvas>
</body>
</html>
<?php
$query = 'SELECT * FROM graph_table';
$result = mysql_query($query);
while($val = mysql_fetch_array($result)) {
$name = $val['test_name'];
echo '<script type="text/javascript"> draw('.$name .'); </script>';
}
?>
You need to add quote's between draw since you're passing text to it. draw(\''.$name.'\'); will make your problem go away.
Try this
<script type="text/javascript">
<?php
$query = 'SELECT * FROM graph_table';
$result = mysql_query($query);
while($val = mysql_fetch_array($result)) {
$name = $val['test_name'];
echo "draw('$name');";
}
?>
</script>
Try the php script inside . Mainly you should add js script just before .
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);
});