issue with autocomplete - php

I'm coding a new website to learn PHP, and coding, and am making an autosuggest that is populated by two mysql tables.
Heres my code (Yes, I'm using mysql, but I'll rewrite this in mysqli once I find a solution!):
suggest.php:
require("./config.php");
$q = $_GET['q'];
$names = '';
$result = mysql_query("SELECT name FROM company WHERE name LIKE '$q%' UNION SELECT cat FROM cat WHERE cat LIKE '$q%' UNION SELECT subcat FROM subcat WHERE subcat LIKE '$q%' LIMIT 10"");
while ($row = mysql_fetch_array($result)) { $names .= $row[name]."\n"; }
echo $names;
?>
index.php ( where the searchbox is)
<form class="form-search span8 offset6">
<input type="text" id='search' name='q' class="input-medium search-query">
<button type="submit" class="btn btn-warning">GO!</button>
</form>
later in index.php (I call jquery.js before):
<script src="public/js/jquery-ui-1.8.22.custom.min.js" type="text/javascript"
charset="utf-8"></script>
<script>
$(function () {
$(document).ready(function () {
$("#search").autocomplete("./suggest.php");
});
});
</script>
The rows I'm trying to populate my autosuggest are the subcat row from the subcat table, the name table from company table, and cat from cat table.
The autosuggest isn't showing up? What's wrong?
Thanks for all help!

Try sending JSON formatted data from php, like:
$names = array();
while ($row = mysql_fetch_array($result)) {
$names[] = $row['name'];
}
echo json_encode($names);//format the array into json data

http://jqueryui.com/demos/autocomplete/
Expected data format The data from local data, a url or a callback can
come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
you are just returning the names selected separated by line breaks

read the documentation of jquery ui autocomplete
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The
value will be inserted into the input element after the user selected
something from the menu. If just one property is specified, it will be
used for both, eg. if you provide only value-properties, the value
will also be used as the label.

from the documentations of jquery autocomplete
http://jqueryui.com/demos/autocomplete/
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
try to pass your data accordingly.

Related

How to make value in autocomplete jquery ui?

In my user table I have id_user and name. My autocomplete searches only by name. I need id_user to input into the database. Usually, we can write id_user as a value attribute in the input tag. This is the code :
Controller :
function get_autocomplete(){
if (isset($_GET['term'])) {
$result = $this->User_model->search($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$arr_result[] = $row->name;
echo json_encode($arr_result);
}
}
}
Model :
function search($name){
$this->db->like('name', $name , 'both');
$this->db->order_by('name', 'ASC');
$this->db->limit(10);
return $this->db->get('user')->result();
}
View :
<input type="text" id="name" placeholder="Name" name="id_user">
<script type="text/javascript">
$(document).ready(function(){
$( "#name" ).autocomplete({
source: "<?php echo site_url('admin/user/get_autocomplete/?');?>"
});
});
</script>
You can fill the autocomplete options with Label/Value pairs.
So the options show the label (e.g. username) and when the user selects one option the value (e.g. id_user) is written to the input field (= the value and is therefor it's displayed in the input field)
So your php code should return a JSON array with label/value pairs
foreach ($result as $row)
$arr_result[] = array('label' => $row->name, 'value' => $row->id_user);
}
echo json_encode($arr_result);
Please take a look at my jsfiddle example - it shows the autocomplete with static data
https://jsfiddle.net/jf7ynxwz/3/
If you don't like the user_id to be written into the input (visible) it's a little bit more complicated. Have a look into the documentation and maybe set the value as an data-html attribute of the input after selection :-)

sending html table data into mysql table

I have a dynamic (via jquery) html table like this:
<form action="index.php" method="post">
<table class="myTable" id="cup">
<tbody>
<tr><td class="header" colspan="6">YOUR SELECTIONS</td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr> //selected
</tbody>
</table>
<input type="submit" value="submit">
</form>
First, the table has only 1 row and 6 cells (except "selections" part). After some conditions satisfied, the cells get filled with some values and the "selected" row is appended into the table via jquery. But my problem here, is not related to jquery.
Each of 6 cells will be inserted into the mysql table part by part. My database table structure like this:
ID | Selection1 |...| Selection6 | Date, time stuffs and other info.
So, I need some code that will do these jobs:
define an array with 6 element.
counter=0;
loop(until there is no traveled cell in the html table)
{
find a cell that is not NULL or its value is not "selections";
array[counter] <-- value of cell;
counter++;
if (counter == 6)
{
insert all of them into the mysql table (?)
counter=0;
}
}//end loop
So, this is my problem. I just can't know how to do it. Should I have to add "id" or "name" stuffs in the html tags or what? :)
EDIT: I don't want you guys to code it for me of course. The thing I couldn't get is how to separate these values 6 by 6 and send them into the database. I just need ideas.
From the html table data you can construct a JSON object. For instance:
var myData = [],
keys = ['ID','Selection1','Selection2', ..... ]
url = './index.php';
$('table').find('tr:gt(0)').each(function( i, row ) {
var oRow = {};
$( row ).find( 'td' ).each( function( j, cell ) {
oRow[ keys[ j ] ] = $( cell ).text();
});
myData.push( oRow );
});
//myData = [ {"ID":"3u3y","Selection1",....},{"ID":"jdjdj",...}.... ]
//now you can use one key to send all the data to your server
$.post( url, { mydata: JSON.stringify( myData ) }, function(d) {
alert( 'Server said, ' + d );
});
//In your PHP script you would look for the data in mydata --> $_POST['mydata']
EDIT
Click the link below to go to a demo.
In THIS DEMO click submit and then look at the console on the right. Click the plus on the left of the failed ajax call and then click the Post tab to examine the data the call attempted to send.
Does that help?

Another/separate value in Select Option

I have a triple select option menu, that works fine now, but when I post/echo it in PHP both the option name and value are the same, so if I want a category that the name is Books, and that could be id=2 example.
I don't know how to put another value in the option, separate the name and value, can someone show me how???
Everything works fine, except I want to have another value than the same name I use to show option name. I hope you understand. :)
My code:
<script type="text/javascript">
var categories = [];
categories["startList"] = ["Wearing Apparel","Books"];
categories["Wearing Apparel"] = ["Men","Women","Children"];
categories["Books"] = ["Biography","Fiction","Nonfiction"];
categories["Men"] = ["Shirts","Ties","Belts","Hats"];
categories["Women"] = ["Blouses","Skirts","Scarves", "Hats"];
categories["Children"] = ["Shorts", "Socks", "Coats", "Nightwear"];
categories["Biography"] = ["Contemporay","Historical","Other"];
categories["Fiction"] = ["Science Fiction","Romance", "Thrillers", "Crime"];
categories["Nonfiction"] = ["How-To","Travel","Cookbooks", "Old Churches"];
var nLists = 3; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 0;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
<form name="tripleplay" action="" method="post">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])" size="5">
</select>
<select name='List2' onchange="fillSelect(this.value,this.form['List3'])" size="5">
</select>
<select name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)" size="5">
</select>
<br><br>
<input type="submit" value="Submit" name="next" />
</form>
<?php
if($_POST['next'])
{
echo $_POST['List1'].'<br>'.$_POST['List2'].'<br>'.$_POST['List3'].'<br>';
}
?>
I am not sure that I understand your intention, but when a form is submitted, the value(s) of select boxes are delivered to the server.
The label property is being displayed in the UI (no need to append a text node).
If you set the value and label properties appropriately, you will be able to submit the form with any value that you want.
For example, the option construction code could be:
var nOption = document.createElement('option');
nOption.setAttribute('value',each);
nOption.setAttribute('label',nCat[each]);
currList.appendChild(nOption);
And you could get the label by using this.selectedOptions[0].label.
Notes:
The coding style that you are using is not very good.
You use inline event handling and do not separate business logic from UI, to name the main issues.
I suggest that you try some kind of JavaScript framework, such as jQuery, which will prevent you from reinventing the wheel and ease you development considerably, leaving you time to do actual work (you may consider a server-side PHP framework as well).
Here is a jsFiddle demo that shows what I believe to be your desired effect.
Edit:
Since you asked about a better approach, I will describe one possibility that slightly abstracts the logic and separates it from the UI.
This is not extremely useful in this type of situations, but it can help in more complex cases.
represent the data hierarchically.
[{
"id": 131,
"label": "Wearing Apparel",
"children": [{
"id": 131,
"label": "Men",
"children": [{
"id": 65,
"label": "Shirts"
}, ...
]
}, {
"id": 143,
"label": "Women",
"children": [{
"id": 133,
"label": "Blouses"
},
...
]
}]
]
this way, you can encode a tree representation of PHP objects into JSON.
Create a jQuery objects that represents the list and generates the markup, since there is little use for it without JavaScript anyway.
Try to make your utility classes such that they could handle more general cases, so that in the future or as your current requirements change, you can still use it with minimal changes to your code.
Try to avoid inline handlers whenever possible (i.e, always).
I have created a jsFiddle example that does not go all the way, but still demonstrates some of those principles: it generates most of the markup on its own, handles the events itself, able to handle data with arbitrary and varying depth.
If I understand your problem is
<option value="Wearing Apparel">Wearing Apparel</option>
that the value and the text(Wearing Apparel) is the same
First of all use another array sructure ( but json would be better )
categories["Books"] = [
["Biography"],
["Fiction"],
["Nonfiction"]
];
An your loop
for (i=0; i<nCat.length; i++) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[i]); // <------- use the "text"
nOption.setAttribute('value',i); // <------- use the index of the step
nOption.appendChild(nData);
currList.appendChild(nOption);
}
In this case
<option value="0">Wearing Apparel</option>
And your POST array will look like
Array ( [List1] => 0
[next] => Submit
)
Where 0 is the ID of the "Wearing Apparel" element
... and 1 is ID of the "Books"

jQuery issue with PHP data and Highcharts

I'm having an issue with the X axis data which is dynamic as it seems to use all the values in the first column.
I'm doing the below:
<div id="season_data_block" style="display: none;">
<?php
foreach($champ_name as $champ_id => $stat_value) {
foreach ($stat_value as $cn => $cs) {
if($champ_id != 0) {
echo '"'.$cn.'",';
}
}
}
?>
</div>
This is putting the PHP data into a hidden div. Then I am using jQuery to access the text from that div.
<script type="text/javascript">
$(document).ready(function(){
var chart_data = $("#season_data_block").text();
$('#stats_chart').highcharts({
chart: {
type: 'column',
backgroundColor: "#F5F5F5",
},
title: {
text: ' '
},
xAxis: {
categories: [chart_data]
},
The issue I'm having is that when the data is inserted into the javascript xAxis, it shows all the php data on the first xAxis value then the rest is defaulted, like below.
First: "name 1","name 2","name 3",
Second: 2
Third: 3
Fourth 4
I want it to be
First: "name 1"
Second: "name 2"
Third: "name 3"
etc. Why is it doing that?
Thanks
Fixed it. I turned my PHP data into another array and then json_encode() that array into a javascript array. Simple :)

Populating a Drop Down Menu (select)

I've been trying to solve my question based off of this answer:
Populate select box from database using jQuery
I've attempted to implement what is said in the answers there but I am not having any luck here. As of now all that appears in the drop down menu is the default "Stone" item that starts in it.
Could anyone spare some time and give me a hand fixing my issue. My code should essentially read from a MySQL database which has over 150 ID's in order starting at 1 and use the corresponding name in the same ID's row to populate the drop down menu on load.
Example of what drop down menu would look like inside of it:
Stone
Grass
Diamond
What corresponding DB would look like:
ID item_name
1 Stone
2 Grass
3 Diamond
The code I'm using to try and do this is:
PHP (process_item_list.php):
$con = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$dbs = mysql_select_db($DB_NAME, $con);
$tableName = "itemlist";
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
jQuery/Javascript
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("process_item_lists.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#tradeItems").html(items);
});
});
</script>
HTML
<select id="tradeItems">
<option value="">Stone</option>
</select>
I'm open to different ways to do this as well, as long as it still fills the drop down menu on load!
Edit: With the help of wirey the PHP issue is fixed. Here is what the results look like from running the PHP file: http://fogest.net16.net/mctrade/php/process_item_list.php
When I run the actual page using the alert boxes which should give me the ID and the item name they both return undefined rather then the correct values.
The results at http://fogest.net16.net/mctrade/php/process_item_list.php doesn't look like what you're expecting, it looks like this:
[ ["1","Stone","images\/stone.png"],
["2","Grass Block","images\/grass_block.png"],
/* snip a lot of rows */
]
But what you are expecting is something like this:
[ { "id":"1", "name":"Stone", "image?":"images\/stone.png"},
{ "id":"2", "name":"Grass Block","image?":"images\/grass_block.png"},
/* and so on */
]
I think that you'll want to use mysql_fetch_assoc() instead of mysql_fetch_row(), that might give you proper output.
Bonus: you can give the response a proper content-type by adding a row before the echo:
header("Content-type: application/json");
echo json_encode($data);
Remark: when I inspected the source of http://fogest.net16.net/mctrade/php/process_item_list.php I found this at the end:
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
This should not be part of the response, it will probably make the JSON parser crash.

Categories