The following php block searches and returns names and i want to select an item and at ajax be able to get other items in the row selected beside "name". How do i separate them with ajax?
<?php
require_once '../php/db_conx.php';
$req = "SELECT name "
."FROM profiles "
."WHERE name LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
Here's ajax.
$(function() {
$( "#SearchInput").autocomplete({
source: 'Search.php',
minLength: 1,
select: function(event, ui) {
$('#Name').append(ui.item.label);
}
});
});
You can use _renderItem method
_renderItem: function( ul, item ) {
$( "#selector" ).text( item.name );// let name is in json
}
Or you can get the name in select event also like,
select: function(event, ui) {
$('#Name').append(ui.item.label);
$( "#selector" ).text( item.name );// let name is in json
}
Try this:
I think you need to parse data from array.
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
Use the variable name you have used.
Read More on: http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx
Thanks
Related
I want to make a dropdown list which is dependable on another dropdown list. Both dropdown list's values are retrieved from database. How can i do that?please help .
Also how can i pass the category name to database mysql query page (list.php).
I currently have this which list all subcategories..but i want to list only particular subcategory depending on category
<script>
$(document).ready(function(){
$.getJSON("getlist.php", function(return_data){
return_data.forEach(function(e,i){
$('#catn').append('<option value= "'+e.catname+'">'+e.catname+'</option>');
});
});
});
$(document).ready(function(){
$.getJSON("list2.php",{'catname':catname},function(return_data){
return_data.forEach(function(h,i){
$('#scatn').append('<option value= "'+h.subcatname+'">'+h.subcatname+'</option>');
});
});
});
list.php
<?php
$catname=$_GET['catname'];
$conn =mysqli_connect("localhost", "root", "", "project");
$sql = "SELECT * FROM catd where catname='$catname'";
$result = mysqli_query($conn, $sql);
$scat_arr = array();
while( $row = mysqli_fetch_array($result) )
{
$catid = $row['cid'];
$catname = $row['catname'];
$scat_arr[] = array("cid" => $catid, "catname" => $catname);
}
echo json_encode($scat_arr);
?>
You can use .change function in JS. While the first dropdown is changing it triggers the ajax with POST method to post to your file list.php(where your query runs).
jQuery(document).ready(function() {
$('#catname').change(function(){
var catname = $(this).val();
$.ajax({
url:list.php,
method:"POST",
data:{
catname:catname
},
dataType:"json",
success:function(data){
var $el = $("#subcatname");
$el.empty();
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Sub Cat Name'));
$.each(data, function(index, value){
$el.append('<option
value="'+value.catid+'">'+value.catname+'</option>')
});
});
You must echo json_encode the output so that ajax recognize the returned value. And then you can append the values by casting it using append.
Hopes this helped.
I have a autocomplete function that works fine but where I want to extend the drop down details a bit. It looks like this:
Datafile (form-lookup.php):
if ($db)
{
$fetch = mysqli_query($db,"SELECT * FROM uni_labels where label_name like '%" . $_GET['term'] . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['label'] = htmlspecialchars_decode($row['label_name']);
$row_array['lookupid'] = $row['id'];
$row_array['address'] = $row['label_address'];
$row_array['number'] = $row['label_number'];
$row_array['postalcode'] = $row['label_postalCode'];
$row_array['country'] = $row['label_country'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysqli_close($db);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
My page that retreives the data looks like this:
$(function() {
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui)
{
$('#step1Name').val(ui.item.address);
$('#lookupid').val(ui.item.lookupid);
$('#vej').val(ui.item.address);
}
});
});
<input maxlength="100" type="text" required="required" class="form-control input-lg" name="step1Name" id="step1Name" />
Everyting works just great, but I would like for my drop down to show both $row_array['label'] and $row_array['address'], and when I select a value in the drop down, the input box will only output the $row_array['label'] value.
In the datafile I have tried to add the address to the label, like this:
$row_array['label'] = htmlspecialchars_decode($row['label_name'])." - ".$row['label_address'];
This displays the value fine in the drop down, but when selecting the choice, the input box of course contains too much data, where I only want it to display the label_name.
Can someone point me in the right direction?
Thanks in advance.
Add this to your autocomplete code:
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
},
focus: function(event, ui) {
return false;
}
So your updated autocomplete code will be like that:
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
return false;
},
focus: function(event, ui) {
return false;
}
});
I want to make the third drop down populated based on selection on second drop down refer value from first and second drop down.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
});
});
$("#sub_cat").change(function() {
$.get('loadsubelement.php?sub_cat=' + $(this).val() + $('#parent_cat').val(), function(data) {
$("#select_subelement").html(data);
});
});
});
</script>
loadsubelement.php
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$sub_cat = $_GET['sub_cat'];
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE categoryID = {$parent_cat}");
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE subcategoryID = {$sub_cat}");
echo '<option value="">Please select</option>';
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['subcategoryID'].'">' . $row['maincategory_name'] . "</option>";
}
?>
I think you have to change your query string like this:
$.get('loadsubelement.php?sub_cat=' + $(this).val() +
"&parent_cat" + $('#parent_cat').val()
You are missing this: "&parent_cat" in your second ajax call.
Or a better way of doing is to send the an object like this:
$("#sub_cat").change(function() {
var dataString = {
parent_cat : $('#parent_cat').val(),
sub_cat : $(this).val()
};
if($('#parent_cat').val() !== ""){ // check if value is selected or not i guessed default value as "".
alert("Please choose the parent value.");
$('#parent_cat').focus(); // apply focus on the element.
return false;
}else{
$.get('loadsubelement.php', dataString, function(data) {
$("#select_subelement").html(data);
});
}
});
jQuery(function($) {
jQuery("#office_id").change(function(){
var inputString=jQuery("#office_id").val();
$.post("?r=reports/summary/loademployees/", {office_id: ""+inputString+""}, function(data){
$('#employee_id').fadeIn();
$('#employee_id').html(data);
}
});
});
});
This is a program triggers when when u change a dropdown containing offices having id as office_id and load employees (another dropdown box having id employee_id) of that office.
I want to make a search box, where you can search between records in the database.
search.php looks like this:
<?php
// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');
$nameser = $_GET['term'];
$names = array();
$result = mysql_query("SELECT name,customerid FROM customers WHERE name LIKE '%".$nameser."%' ORDER BY name ASC");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['customerid'];
$row_array['value'] = htmlentities($row['name']);
array_push($names,$row_array);
}
echo json_encode($names);
?>
Javascript part looks like this:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
However, this gives the error:
ReferenceError: item is not defined
What I want to happen is, that when I click something in the result list, I get redirected to the url
customers.php?action=view&cid={CustomerID}
Anyone got an idea?
EDIT:
Correct Javascript code that works:
$("#tags").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
window.location = ("customers.php?action=view&cid=" + ui.item.id)
//$('#tags').val(ui.item.id);
//return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href='customers.php?action=view&cid="+ item.id + "'>"+ item.label + "</a>" )
.appendTo( ul );
};
i have a demo with a working example in jsfiddle. you can see it here:
the key is to get a valid url value in the autoselect select method. be sure to console.log the ui value so you can see what is available for you to use. i was able to use the standard ui.item.value value to send the user to another page.
to test my demo:
1.) go into the input box and enter "a".
2.) select "http://www.utexas.edu"
3.) the new page will load.
I've been working on this for a couple of hours and it should work but i'm missing something!
basically, i'm using jquery autocomplete with json source, with 2 values id and description.
Description should show up in suggestions and if item is selected and ID passed to a hidden field ( the field is not hidden currently for testing purposes)
here's my code:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php",
minLength: 3,
formatItem: function(data, i, n, value) {
return value.split("|")[1];
}
});
$("#CurrentProv").result(function(event, data, formatted) {
if (data)
$("input#fid").val(data[0]);
});
});
//PHP valid json output
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'].'|'.$row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
I've searched and done various variations and still doesn't work!!! My brain is shutting down!!!!!!!!
First, switch to using the actual jQuery UI autocomplete.
You'll have to sort out how to format your items on the server side, or in your JSON callback, because formatItems is not supported anymore. Check out this guide for some help.
Now that you've done that, here's how it will look:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.value);//or ui.item.desc perhaps
}
});
});
Working tweaked PHP code and JS as Ryley suggested:
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'];
$searchArray['id'] = $row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.id);//or ui.item.desc perhaps
}
});