I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;
Related
I would like to ask a question and I need a little help from you guys.
I would like to use jquery Datatable plugin in my project but something going wrong.
The table is displayed properly, but none of the datatable functions working.
Here is my code:
function get_answer(get_date, get_id) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var date = get_date;
var id = get_id;
var data = {
'action': 'get_answers_ajax',
'date': date,
'id': id
};
var table_structure = '<table id="result-' + id + '" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#tabs-' + id).append(table_structure);
jQuery.post(ajaxurl, data, function (response) {
if (response) {
var obj = JSON.parse(response);
var heads = [];
var results = [];
jQuery.each(obj, function (key, res) {
if (jQuery.inArray(res.label, heads) == '-1')
{
heads.push(res.label);
}
results.push(res.value);
});
var head = jQuery('#tabs-' + id + ' .result_head tr');
head.empty();
jQuery.each(heads, function (key, value) {
head.append('<th>' + value + '</th>');
});
var body = jQuery('#tabs-' + id + ' .result_body');
body.empty();
if (results.length > 0) {
body.append('<tr role="row" class="odd">'); // Open tr
var count_heads = heads.length;
var count_answ = 0;
jQuery.each(results, function (key, value) {
if (value.substring(0, 4) == 'http') {
body.find('tr').last().append('<td><img src="' + value + '" alt="none" width="200px" height="200px" /></td>');
} else {
body.find('tr').last().append('<td>' + value + '</td>');
}
count_answ++;
if ((count_answ % count_heads) == 0) {
body.find('tr').last().find('td').last().after('</tr>');
body.find('tr').last().after('<tr role="row" class="even">');
}
});
body.find('tr').last().after('</tr>'); // Close tr
}
}
});
jQuery('#result-' + id).dataTable(
{
"ordering": true,
"searching": true
}
);
The heads and the reults array looks like this:
Heads => ["Eredmény", "Felhasználó", "Dátum"]
Results => ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"]
My PHP function which one gives back the data is this:
function get_answers() {
global $wpdb;
$date = $_POST['date'];
$form_id = $_POST['id'];
$date_pice = explode(' - ', $date);
$question = array();
$answer = array();
$sql_answers = "SELECT lead.date_created, detail.field_number, detail.value, detail.form_id, meta.display_meta FROM wp_rg_lead_detail AS detail INNER JOIN wp_rg_lead AS lead ON detail.lead_id = lead.id INNER JOIN wp_rg_form_meta AS meta ON detail.form_id = meta.form_id WHERE lead.date_created BETWEEN '{$date_pice[0]}' AND '{$date_pice[1]}' AND detail.form_id = '{$form_id}' ";
$answers = $wpdb->get_results($sql_answers);
foreach ($answers as $ans_info) {
$meta = self::bsp_unserialize($ans_info->display_meta);
foreach ($meta[fields] as $fields) {
if ($fields["id"] == $ans_info->field_number) {
$question["kerdes"] = $fields["label"];
$answer["valasz"] = $ans_info->value;
}
}
$toJSON[] = array("label" => $question["kerdes"], "value" => $answer["valasz"]);
}
echo json_encode($toJSON);
die();
}
So, the table shows all of the data in it, but If i would like to search or ordering or paginating nothings works.
Any hint about it?
Thx a lot
I could solve the problem.
I just modifed the append method, and now I making a html string with the ready html element and I jut append that at the end of the process.
jQuery(document).ready(function () {
var table_structure = '<table id="result" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#table').append(table_structure);
var heads = ["Result", "User", "Date"];
var results = ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"];
jQuery('.result_head tr').empty();
jQuery.each(heads, function (key, value) {
jQuery('.result_head tr').append('<th>' + value + '</th>');
});
var body = jQuery('.result_body');
body.empty();
if (results.length > 0) {
var count_heads = heads.length;
var count_answ = 0;
var html = "";
jQuery.each(results, function (key, value) {
if ((count_answ % count_heads) === 0) {
html += '<tr>';
}
if (value.substring(0, 4) == 'http') {
html += '<td><img src="' + value + '" alt="none" width="200px" height="200px"/></td>';
} else {
html += '<td>' + value + '</td>';
}
count_answ++;
if ((count_answ % count_heads) === 0) {
html += '</tr>';
body.append(html);
html = '';
}
});
}
jQuery('#result').dataTable(
{
"ordering": true,
"searching": true
}
);
});
When I start writing on my input, my results appear with html tags, for example, if I search for "t" I get: Title<p><span>Content</span></p>. And I want Title Content, without no html tags.
This is my php:
$search = isset($_GET['term']) ? $_GET['term'] : "";
$pdo = conecting();
$read = $pdo->prepare("SELECT * from articles WHERE title LIKE ?");
$read ->bindValue(1, "%$search%", PDO::PARAM_STR);
$read ->execute();
$data = array();
while($res = $read ->fetch(PDO::FETCH_ASSOC))
{
$data[] = $res['title'].'-'.$res['content'];
}
echo json_encode($data);
This is my jQuery to start autocomplete:
$('.j_autocomplete').autocomplete({
source: 'http://localhost/project/tpl/search.php'
select: function(event, ui){
var get= ui.item.value;
returndata(get);
},
change: function(data)
{
returndata($(this).val());
}
});
Do you know how to solve this?
Try using this way:
Add this code after autocomplete initialization:
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item + "</a>")
.appendTo(ul);
};
Like this:
$('.j_autocomplete').autocomplete({
source: 'http://localhost/project/tpl/search.php'
select: function(event, ui){
var get= ui.item.value;
returndata(get);
},
change: function(data)
{
returndata($(this).val());
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item + "</a>")
.appendTo(ul);
};
How do I Auto Capitalize all the value of my dynamic text box. I want on submit for security purposes. I used strtooper in PHP but it has an array problem. And I used auto capitalization using CSS but if the value is already submitted to database it is not working, it's still the same as the value I inputted. Anyone can help me.
main form:
<script type='text/javascript'>
/* attach a submit handler to the form */
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
var mytxt1 = [];
var mytxt2 = [];
$(".car_brand").each(function () {
mytxt1.push($(this).val());
});
$(".car_model").each(function () {
mytxt2.push($(this).val());
});
e.preventDefault();
var perfTimes = $(this).serialize();
$.post("maintenance_function.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.location.href = data.redirect;
}
}, "json");
});
});
<script>
var nitem =0;
var ntotal = 0;
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'Car Manufacturer: <input type="text" class="car_brand" id="' + nitem + '" required> ' +
'Car Model: <input type="text" class="car_model" id="' + nitem + '" required>' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem).each(function(){
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
</script>
Function form:
<?php
include('connect.php');
$mydata = $_POST["results"];
//echo $mydata;
parse_str($mydata);
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$errors = [];
if(!isset($_POST["txt1"])){
$errors[] = array(
'error_code' => 1,
'message' => 'Please add a text box.'
);
}
if(empty($errors)) {
for($i=0;$i<=count($_POST["txt1"])-1;$i++)
{
//if (trim($_POST["txt1"][$i]) != "" && trim($_POST["txt2"][$i]) != "" && trim($_POST["txt3"][$i]) != ""){
mysql_query("INSERT INTO car_maintenance VALUES ('', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."')");
//}
}
$response = array(
'message' => 'Successfully Added',
'redirect' => "car_maintenance.php"//add here
);
echo json_encode($response);
}
else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
?>
use this on the string you want to capitalize in the php file:
$newstring = ucwords(strtolower($string1));
this will create “title case,” where the first
letter of each word is in uppercase and the rest of the letters are in lowercase, hopw this is what you meant.
if you want all letters capital, use this:
$newstring = strtoupper($string1);
In css
input {text-transform:uppercase;}
In javascript
document.getElementsByTagName('input').value = document.getElementsByTagName('input').value.toUpperCase()
I am having trouble accesssing a jquery array which is getting JSON data from a PHP script. If I hard coded the array in jquery it worked fine. I checked using cosole.log. Both nproducts and products array giving the same values. Please note that nproduct has hard coded values where are product is getting from a PHP script. Can someone put my in the right direction. Thanks
here is the PHP Code
while ($row = oci_fetch_array($result,OCI_ASSOC)) {
$shop[$row['WH_DESCRIPTION']] = array(
'pic' => $row['WH_PIC'],
'price' => $row['WH_PRICE']
);
}
echo json_encode($shop);
here is the jquery. If I use nproduct then productsRendering function works fine but if I use product then it print containsValue for name and pic and undefined for price. It seems that the product array does not have any values in the productRendering function where as getJSON is returning values.
<script type="text/javascript">
var cart = (function ($) {
var productsOffset = 3, products = [],
nproducts = {
'Black T-shirt': {
pic: 'black-controller.png',
price: 15
},
'Green T-shirt': {
pic: 'green-kentucky.png',
price: 18
},
'Brown T-shirt': {
pic: 'brown-computer.png',
price: 25
}
};
$.getJSON('shop.php', function(data) {
products = data;
console.log(data); //showing values here
console.log(products); //showing values here
console.log(nproducts); //showing values here
});
function render() {
productsRendering();
};
function productsRendering() {
var catalog = $('#catalog'),
imageContainer = $('</div>'),
image, product, left = 0, top = 0, counter = 0;
console.log(products); //does not have values here
for (var name in products) {
product = products[name];
image = createProduct(name, product);
image.appendTo(catalog);
if (counter !== 0 && counter % 3 === 0) {
top += 147; // image.outerHeight() + productsOffset;
left = 0;
}
image.css({
left: left,
top: top
});
left += 127; // image.outerWidth() + productsOffset;
counter += 1;
}
$('.draggable-demo-product').jqxDragDrop({ dropTarget: $('#cart'), revert: true });
};
function createProduct(name, product) {
return $('<div class="draggable-demo-product jqx-rc-all">' +
'<div class="jqx-rc-t draggable-demo-product-header jqx-widget-header-' + theme + ' jqx-fill-state-normal-' + theme + '">' +
'<div class="draggable-demo-product-header-label"> ' + name + '</div></div>' +
'<div class="jqx-fill-state-normal-' + theme + ' draggable-demo-product-price">Price: <strong>$' + product.price + '</strong></div>' +
'<img src="images/t-shirts/' + product.pic + '" alt='
+ name + '" class="jqx-rc-b" />' +
'</div>');
};
function init() {
render();
};
return {
init: init
}
} ($));
$(document).ready(function () {
cart.init();
});
</script>
productsRendering() gets called before ajax request completes. Consider calling productsRendering() inside the ajax callback.
This is because the browser does not interpret the response body as JSON. Try setting Content-Type header in php before echoing response:
header('Content-Type', 'application/json');
I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);