hoping someone can help me out with something.
I've got a piece of code which allows the Jquery Autocomplete. What I'm wanting to do is to use the ID(primary key) from my MySQL table and then use that to POST on to another screen.
How would I go about getting the ID into a hidden value from the Jquery code?
Here are my snippets.
Jquery
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'JQUERYTEST.php'
});
});
</script>
Html
<div class="ui-widget">
<label for="shop">Shopname: </label>
<input id="shop">
</div>
Php/MySQL
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'aurora';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM shops WHERE shopname LIKE '%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['shopname'] . ' - '. $row['streetaddress'] . ' - ' . $row['postcode'];
}
//return json data
echo json_encode($data);
?>
Thanks!
Firstly, you will have to use an Ajax call to get the data from the server. So, change your autocomplete function and add an ajax call to receive a response. Then you will have to loop the JSON array in jquery. I have created the id as the whole string with shopname, streetaddress and postcode. Currently, your code doesn't inserts the ID parameter from the database. You can create an id depending on your needs. Then dynamically I have created the HTML and then placed it inside the <div class="ui-widget">
<script>
$( function() {
$( "#skills" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
var html = "";
$.each(data, function(i, item) {
var arr = item.split('-');
html += "<label for='shop'>Shopname:"+arr[0]+" </label><input id='"+item+"' type='hidden'><br>";
});
$('.ui-widget').html(html);
}
});
}
});
});
</script>
Try this out. I hope this helps you.
Related
I'm building an autocomplete with jQuery autocomplete. To accomplish this I have stored 216 data records of industries in a table. I would like to fetch that table and use in javascript array for the autocomplete. You can see what I have tried so far but I'm getting null. My question is how do I fetch the data from the database and make it an array I can use in a javascript array for the autocomplete?
table
id | industryName
1 | Air Transport
2 | Agriculture
...
autocomplete.php
<div class="ui-widget">
<label for="industries">Industries: </label>
<input id="industries">
</div>
<script>
$.ajax({
url : 'industries.php',
type : 'GET',
success : function(data){
var availableIndustries = jQuery.parseJSON(data);
$( function() {
$( "#industries" ).autocomplete({
source: availableIndustries
});
} );
}
});
</script>
industries.php
include 'includes/database.php';
$sql = "SELECT * FROM industries";
$result= $conn->query($sql);
echo json_encode($result);
Is your naming right? Example is wrong..
Also, add and exit; after echo json_encode($result);
I found a solution that works for me.
autocomplete.php
<div class="ui-widget">
<label for="industries">Industries: </label>
<input id="industries">
</div>
<script>
var validOptions = <?=$json_array?>;
previousValue = "";
$('#industries').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
</script>
industries.php
//bind to $name
if ($stmt = $conn->prepare("SELECT Industry FROM industries")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
is that posible to load same data with jquery tooltip?
for example i have a data like this.
<div class="content"><span id="user_801130021">text1</span></div>
<div class="content"><span id="user_801130021">text2</span></div>
<div class="content"><span id="user_1301193710">text3</span></div>
the tooltip only showing for text1 and text3 but not showing data for text2, i think that because same id there.
here my js code
$(document).ready(function(){
// initialize tooltip
$( " span" ).tooltip({
track:true,
open: function( event, ui ) {
ui.tooltip.css("max-width", "100%");
var id = this.id;
var split_id = id.split('_');
var userid = split_id[1];
$.ajax({
url:'fetch_details.php',
type:'post',
data:{userid:userid},
success: function(response){
// Setting content option
$("#"+id).tooltip('option','content',response);
}
});
}
});
$(" span").mouseout(function(){
// re-initializing tooltip
$(this).tooltip();
$('.ui-tooltip').hide();
});
});
my fetch_details.php
<?php
$userid = $_POST['userid'];
$query = $db->prepare ("SELECT * FROM master_post WHERE id_master_post =".$userid);
$query->execute();
$html = '<div>';
while ($value = $query->fetch()) {
$information = html_entity_decode ($value['information']);
$dom = new DOMDocument();
#$dom->loadHTML($information);
$image = $dom->getElementsByTagName('img')->item(0)->getAttribute('src');
$html .= "<img src='".$image."' height='300px' width='250px'>";
}
$html .= '</div>';
echo $html;
?>
If they are not going to be unique as in your code, you can do different things.
Class
You can use class instead of id.
Use <span class="user_801130021"> instead of <span id="user_801130021">
You can access them by using basic jQuery selectors : $('.user_801130021')
HTML5 Data Attributes
Another option is using them as HTML5 data attributes which is so much better in my opinion. Their format is data-*.
<span data-user="user_801130021">
You can get data-user value by $('span').data('user') and change it by $('span').data('user', value)
For example, if you changed id to data-user, you must change var id = this.id; to var id = this.data('user');. Then everything will be work as it must.
i found the trick.
use looping number to create unique id.
here my code.
$np = 0;
while ($value = $query->fetch()) {
<div class="content"><span id="user<?php echo np++ ?>_801130021">text1</span></div>
}
I have a search form where I want to display suggestions via jQuery autocomplete when 3 characters are typed. The suggestions are drawn from a mySQL DB.
What happens: jQuery does successfully transmit the typed chars to the PHP file, where they successfully get embedded in an mySQL query.
When I open the PHP file separately with an assumed search term, f.e. like this: /soplogsearch.php?term=xyz it works perfectly and I see the aimed at result of echo json_encode($return_arr);
but back on the HTML search form file autocomplete doesn't suggest a thing. I have no errors in the console. I tried to echo the json_encode elsewhere on the HTML file and its output was Null.
I have made a fiddle for the (very simple) Javascript/jQuery and HTML set up: https://jsfiddle.net/9bf6s07f/1/
the relevant PHP code looks like this:
if (isset($_GET['term']))
{
$term = $_GET['term'];
$termwild = "%$term%";
$return_arr = array();
$service = mysql_query("SELECT DISTINCT service FROM master WHERE service LIKE \"" . $termwild . "\"");
while ($data = mysql_fetch_array($service))
{
$return_arr[] = $data[0];
}
json_encode($return_arr);
echo json_encode($return_arr);
}
EDIT: For quicker access I'm including the HTML and jQuery parts of the code here instead of link you to the fiddle https://jsfiddle.net/9bf6s07f
<body>
<label>Service:</label>
<input type='text' name='' value='' class='auto'>
</body>
and jQuery:
$(document).ready(function() {
$(function() {
$(".auto").autocomplete({
source: "soplogsave.php",
minLength: 3
});
});
});
Does someone know what I'm doing wrong? I tested autocomplete separately with a set of javascript variables and it worked fine.
EDIT 2: Because all of the comments seem to imply my PHP is wrong and I'd have an error in the console, I made a screenshot from the network tab of the console: http://i.imgur.com/i6nAQ98.png
This is how I have achieved it in my code:
PHP
$param = $_GET["term"];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND (product_code LIKE '%{$param}%' OR product_name LIKE '%{$param}%'); ";
//FB::info($stk_adddep);
//echo $stk_adddep;
//die();
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['itemCode'] = $row['product_code'];
$row_array['itemDesc'] = $row['product_name'];
//$row_array['itemPrice'] = $row['unit_cost_price'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
//mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
And then javascript
$(document).ready(function(){
// Use the .autocomplete() method to compile the list based on input from user
var url10 = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_cocktails.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>';
$('#itemCode').autocomplete({
source: url10,
minLength: 1,
select: function(event, ui) {
var $itemrow = $(this).closest('tr');
// Populate the input fields from the returned values
$itemrow.find('#itemCode').val(ui.item.itemCode);
$itemrow.find('#itemDesc').val(ui.item.itemDesc);
//$itemrow.find('#itemPrice').val(ui.item.itemPrice);
// Give focus to the next input field to recieve input from user
$('#itemQty').focus();
return false;
}
// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemCode + " - " + item.itemDesc + "</a>" )
.appendTo( ul );
};
See if you can maybe apply this to your code?
The answer was posted in the comments by user #n00dl3.
I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});
I'm trying send select query and set the result as value attribute for different input fields, the query should be sent upon selecting a value from dropdown list. After doing some researches I found this can be reached through jQuery.
jQuery will send request to php file which contains my query and fetch result and then return values in json format. At this point everything is working great, my php file is working and return valid json data but I cannot get these data append in the input fields I have. Here is my script that should run the php file and return the results in json then append results in text fields.
Check my code on fiddle
<script>
var flight_destination = $('#destination).text();
var flight_departure = $('#departure).text();
var flight_arrival = $('#arrival).text();
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){
var flight_destination = data[1];
var flight_departure = data[2];
var flight_arrival = data[3];
}
}
$('#destination').val(flight_destination);
$('#departure').val(flight_departure);
$('#arrival').val(flight_arrival);
})
</script>
getFlightData.php
<?php
include "dbConnect.php";
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => $row['departure'],
'arrival' => $row['arrival']
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
GOOD NEWS
A friends of mine helped me out with a syntax error in data: line. I did change it from data:'flight_number='+$('#flight_number').val(), to data:{'flight_number':$('#flight_number').val()},
In browser console window the json objects returned perfectly on change the drop down list value but still cannot append these objects to the input fields as value attribute
Update 2
Now I have this Still the data returned in the browser's console window perfectly, but the only what appended in the first text field is [object]
of the browser after selecting option from drop down list
Update 3
With great help and effort from #satyrwilder I'm now able to retrieve the first text field value. This is working version of the script snippet
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
I'm now looking forward to append the datetime-local values as well. I will keep this question updated regularly until it's 100% compelted
you must declare what type of data going to receive your inquiry.
dataType: "json"
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){ ... },
dataType: "json", //<--------- this
});
Documentation of $.ajax()
And header from json in the start of you code php
For JSON:
header('Content-Type: application/json');
For JSON-P:
header('Content-Type: application/javascript');
Finally I came to the final working code where everything is working perfectly. First I'd like to thank #satyrwilder for correcting my javascript part.
Here is the final code, which appends values from database into text and datatime-local fields using jquery + php
getFlightDate.php
<?php
header('Content-Type: application/json');
include "dbConnect.php";
function datetime()
{
return date( 'Y-m-d\TH:i:s', time());
}
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => datetime($row['departure']),
'arrival' => datetime($row['arrival'])
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
print.php
<?php
include "dbConnect.php";
$flight_numbers = mysql_query("SELECT flight_number FROM flights");
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<select id="flight_number">
<?php while($row = mysql_fetch_array($flight_numbers))
{
Print "<option>".$row['flight_number'] . "</option> ";
}
?>
</select>
<br>
<input type="text" id="destination">
<input type="datetime-local" id="departure" />
<input type="datetime-local" id="arrival" />
<script>
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
</script>
</body>
</html>
The trick was to change the datetime format before json_encode, because datetime-local input fields shows values in specific format which is 2014-12-05T08:30:59 -> Y-m-d\TH:i:s