Jquery autocomplete custom HTML results - javascript

I'm building a search with jQuery UI Autocomplete (http://jqueryui.com/demos/autocomplete/)
I am also utilizing the jQuery UI Autocomplete HTML Extension so I can style the search nicely and display icons according to the category where the search result is in.
My problem is, when I click on a result which looks like this:
(Category Icon) Pink Floyd - Category
It comes out like this in the search input field:
<div class="search_icons"><img src="images/ico/search_icon_rock.png" class="search_pic_radius"></div>Pink floyd<div class="autocomplete_category"> Rock</div><div class="artist_id_search">15</div><div class="artist_name_search">pink-floyd</div>
This is how my search.php looks like:
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT url_name,name,category,id FROM artists WHERE name LIKE :term OR category LIKE :term LIMIT 10');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
if($row['category'] == '1') { $category_icon = '<div class="search_icons"><img src="images/ico/search_icon_rock.png" class="search_pic_radius"></div>'; }
if($row['category'] == '2') { $category_icon = '<div class="search_icons"><img src="images/ico/search_icon_pop.png" class="search_pic_radius"></div>'; }
$return_arr[] = $category_icon . $row['name'] . '<div class="autocomplete_category"> ' . $row['category'] . '</div>'. '<div class="artist_id_search" id="artist_id_search">' . $row['id'] . '</div>'. '<div class="artist_name_search" id="artist_name_search">' . $row['url_name'] . '</div>' ;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
What I'm trying to achieve is, when clicking on something on the autocomplete it should submit the form with the value from the last two div's artist_id_search and artist_name_search so on submit the next page would become whatever.php?id=15&artist=pink-floyd
What I have tried is to remove the unnecessary parts from the search string with the split function but then I just ended up with the id and the url_name parameters in the search field which didn't really achieve anything also it didn't really work reliably with changing icon names and such.

Well instead of returning HTML from the PHP service you have made in JSON, you should be returning a proper JSON like in the form of
[
{"id":"15","name":"pink-floyd","value":"Pink Floyd"},
{...
]
then handle it in your javascript as:
$( "#your_input_id" ).autocomplete({
source: "your_php_page.php",
minLength: 2,
select: function( event, ui ) {//callback function when you select an item
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
window.location.href = 'whatever.php?id=ui.item.id&artist=ui.item.name';
}
});
Hope you get it sorted :)

Related

Get selected variation price and sku and display it to single product in woocommerce

I want to display current selected variation price and sku # woocommerce_before_single_product_summary
How do I get the values and display them on top of the page inline with styling?
I'm working with these resources:
Get and display the selected variation SKU in WooCommerce
Get currently selected variation and data from Woocommerce variable product
WooCommerce: show current SKU and GTIN in variable product page
This is what I have:
// Display product variations SKU and price
add_filter( 'woocommerce_available_variation', 'display_variation_sku_and_price', 20, 3 );
function display_variation_sku_and_price( $variation_data, $product, $variation ) {
$html = ''; // Initializing
// Inserting SKU
if( ! empty( $variation_data['sku'] ) ){
$html .= '</div><div class="woocommerce-variation-sku">' . __('SKU:') . ' ' . $variation_data['sku'];
}
// Inserting price
if( ! empty( $variation_data['price'] ) ){
$html .= '</div><div class="woocommerce-variation-price">' . __('price:') . ' ' . $variation_data['price'];
}
// Using the variation description to add dynamically the SKU and the price
$variation_data['variation_description'] .= $html;
return $variation_data;
}
add_action('woocommerce_before_single_product_summary', 'display_product_sku_and_price', );
function display_product_sku_and_price() {
global $product;
echo '<p>' . __("SKU:") . ' ' . $product->get_sku() . '</p>';
echo '<p>' . __("Price:") . ' ' . $product->get_price() . '</p>';
}
I can make it work inside variations form but not move it outside/up.

AJAX won't call the PHP file when using $.post()

I have been trying to export a search result to an Excel file (type .xls), before this, I have been using purely PHP and it works.
However, my client requests to have "live search" effect, so I have to shift to AJAX.
Here is the starting point: User clicks "Export" button, and in the javascript (in the main php file viewdata.php):
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
....
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$.post("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
cbXDate is an input field of type date to let user choose a date from whence to export the data, and cbsearch is a text input field to include a search keyword. console commands are added to see where the code execution has went through.
in the export_contact.php:
<?php
echo '<script> console.log("Export PHP activated."); </script>';
?>
I removed the PHP MySQL data selection code just to debug the problem (full source code below).
Problem is: export_contacts.php is never called. The "Export PHP activated" message never popped up in the console. The console only displayed the data values and "Completed", i.e. export_contacts.php was never called.
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Complete
Out of curiosity, I replaced $.post(...) with $("#export_div").load(...) and the console message showed up:
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$("#export_div").load("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Export PHP activated.
Complete
But this is not what I want, I want to write the output to a file, not display them in a div in the webpage. However, the data shown in the "export_div" div is correct, but the header part is not running, I know the quirkyness in header() calls, but I didn't output anything before the header() calls (unless output from the calling viewdata.php file also count?), here is the full export_contacts.php source code:
<?php
include("./php/auth.php");
$guid = $_POST['sGuid'];
$date = $_POST['sDate'];
$skey = $_POST['sKey'];
$searchKey = $_POST['sKey'];
if($searchKey == "")
{
$skey = "'%'";
}
else
{
$skey = "'%".$searchKey."%'";
}
$sql = "SELECT *, FROM_UNIXTIME(ROUND((date / 1000), 0) + 46800) AS date
FROM contacts
WHERE owner = '$guid' AND contact <> ''
AND (contact LIKE $skey OR name LIKE $skey) ";
if(!empty($date))
{
"AND date >= '$date' ";
}
$sql .= "ORDER BY contact;";
if($result = mysqli_query($link, $sql))
{
$columnHeader = '';
$columnHeader = "Owner" . "\t" . "Contact" . "\t" . "Name" . "\t" . "SaveDate" . "\t";
$setData = '';
while($rows = mysqli_fetch_assoc($result))
{
$rowData = '';
foreach ($rows as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// in case of .load() used,
// code works up until this point
// code doesn't work since here...
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=contact_".$guid.".xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
// until here
// this will show in console in case of .load() used
echo '<script> console.log("Export PHP activated."); </script>';
die();
}
else
{
echo "<script>window.alert('ERROR: '".mysqli_error($link).")</script>";
}
include("./php/cleanup.php");
?>
This code is working in the pure PHP version. I don't know why this header() part isn't working in here, could be due to its output got redirected to the div?
To make things clear, my question is: "Why $.post(...) isn't calling the PHP file, while $("#export_div").load(...) did?".
The header() part is just a sub question, and is fine if it's ignored.
As Kmoser pointed out, I was doing things wrong. None of the tutorial sites I visited did mention that $.post() will not return any result at all, while my php code is expecting the return of the search result and write them in a file in the header() calls.

JQuery auto complete with links

I'm in the process of establishing a website which uses JQuery's auto complete to give users suggestions on pages. I store the page ID and title in a SQL database (connecting using PDO). At the moment, I've got the auto complete feature working, however, I am absolutely stumped on how to get the auto complete list to turn into clickable links which direct the user to the relevant page based off the page ID in the database.
Here's my search.php file
<?php
require('includes/connect.class.php');
if (isset($_GET['term'])) {
$return_arr = array();
try {
$stmt = $conn->prepare('SELECT id, locationName FROM locations WHERE locationsName LIKE :term');
$stmt->execute(array(
'term' => '%' . $_GET['term'] . '%'
));
while ($row = $stmt->fetch()) {
$return_arr[] = $row['locationName'];
}
}
catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
?>
and my JavaScript
$(function() {
$(".locationlist").autocomplete({
source: "search.php",
minLength: 1
});
});
The database looks like this
Locations
|---ID---||---locationName---|
| 1 || Test1 |
| 2 || Test2 |
----------------------------
I've done some research, and I believe I need to modify JQuery to display an array of objects. I'm not too sure how to do this.
What would be the best way to have my auto complete list get the page ID from the SQL database and become clickable links?
You don't actually need for clickable links there. You can redirect the page within the autocomplete's select event , where you have access to the selected item object:
ui (Type: Object):
item (Type: Object):
An Object with label and value properties for the selected option.
ui.item.value will be the page ID generated with your PHP
$(".locationlist").autocomplete({
source : "search.php",
minLength: 1,
select : function(event, ui){
// You may need to change this part, as I don't know the exact values:
location.href = "http://your-site.com/" + ui.item.value;
}
});
As for your PHP, you can modify the output array like so:
while ($row = $stmt->fetch()) {
$return_arr[] = array(
'value' => $row['ID'],
'label' => $row['locationName']
);
}

Populating second dropdown list depending on first one in a Wordpress page

Hello and have a nice day everyone.
I, being not an actual coder, managed to overcome dropdown list issue in basic html, then in php using javascript in Dreamweaver. I even made it using Ajax without reloading the page. Thanks to those people who created it in plus2net. Here is the link i benefited from. http://www.plus2net.com/php_tutorial/php_drop_down_list.php
My problem is with a Wordpress page. Wordpress has a buit-in function for generating dropdown lists for pages, posts etc. I used wp_dropdown_pages function, whose reference can be found here: http://codex.wordpress.org/Function_Reference/wp_dropdown_pages
and in post-template.php file function is like this:
function wp_dropdown_pages( $args = '' ) {
$defaults = array(
'depth' => 0, 'child_of' => 0,
'selected' => 0, 'echo' => 1,
'name' => 'page_id', 'id' => '',
'show_option_none' => '', 'show_option_no_change' => '',
'option_none_value' => ''
);
$r = wp_parse_args( $args, $defaults );
$pages = get_pages( $r );
$output = '';
// Back-compat with old system where both id and name were based on $name argument
if ( empty( $r['id'] ) ) {
$r['id'] = $r['name'];
}
if ( ! empty( $pages ) ) {
$output = "<select name='" . esc_attr( $r['name'] ) . "' id='" . esc_attr( $r['id'] ) . "'>\n";
if ( $r['show_option_no_change'] ) {
$output .= "\t<option value=\"-1\">" . $r['show_option_no_change'] . "</option>\n";
}
if ( $r['show_option_none'] ) {
$output .= "\t<option value=\"" . esc_attr( $r['option_none_value'] ) . '">' . $r['show_option_none'] . "</option>\n";
}
$output .= walk_page_dropdown_tree( $pages, $r['depth'], $r );
$output .= "</select>\n";
}
/**
* Filter the HTML output of a list of pages as a drop down.
*
* #since 2.1.0
*
* #param string $output HTML output for drop down list of pages.
*/
$html = apply_filters( 'wp_dropdown_pages', $output );
if ( $r['echo'] ) {
echo $html;
}
return $html;
}
With this function and its arguments, it is very easy to populate a dropdown list, and get what you want. However my goal is to generate a second drop down with the selected value of the first one. Like the first one is car brands, and the second one is models.
To do this how can i use wp_dropdown_pages() function? If I must, how can i do this using AJax or just Javascript?
Thank you all in advance.
You can't use PHP once the page is on screen, without reloading or AJAX.
You could create the second dropdown menu(s) right away and hide them at first. Then make the correct one visible when the first dropdown menu is clicked/changed using jQuery.
Or use an AJAX call to a function that will return the correct dropdown menu HTML.
In more detail:
look into how you can grab the information of a changed
dropdown menu (an option is selected) using jQuery.
look into how to use AJAX in WordPress environment. Create the jQuery to call
the PHP function that will return your HTML.
In your AJAX call send along the grabbed information of the dropdown menu.
On successful AJAX function you need to tell jQuery to echo the output.

How can I specify a specific value in a column retrieved via php?

I would like to add an if statement regarding the 'type' column. Is there something after the .attr('type') which will allow me to specify a particular value for type?
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
So $(this).attr('type'); is loading all the rows in my tables 'type' column value. eg:
Table
Name, Address, Type*
Name1, Address1, TypeA,
Name2, Address2, TypeB,
Name3, Address3, TypeA,
etc
How can I 'get access' to what actually the value of the 'type' column; eg. $(this).attr('type').<something>('TypeA');
Is this possible?
Edit2: map_process.php end
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'description="' . parseToXML($row['description']) . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
You have two options:
(1) If you have full control over the ajax page you are calling, the best solution would be to:
"send the selected checkbox value into map_process.php and get the
selected value from table and update the markers again in Map." –
Krish R
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$.get("map_process.php?checkboxval=" + cbVal, function (data)
{
//do something with the data returned
});
//PHP
$query = "SELECT * FROM markers where type = '".$_GET["checkboxval"]."'";
(2) If you don't have control over the source of the ajax call (for example from a third party source), OR you want to return all markers every time, consider using the jQuery Filter method.
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$(data).filter(function(index,val)
{
return $(val).attr('type') === cbVal;
}).each(function ()
{
//do something with the data returned
});
See the example for option (2) on this JSFiddle

Categories

Resources