I am trying to autofill input text 1 and fill a 2nd input based on the select on field 1. My sql works great.
In the html form - ids are formfieldname1 and formfieldname2
The autocomplete works on field 1, but wont carry the 2nd value over to the 2nd text field
At the bottom of my form field I have this
<script>
// JQUERY AUTOCOMPLETION
$(function() {
$( "#formfieldname1" ).autocomplete({
source: "vessels6.php",
minLength: 1, //search after one characters
});
});
</script>
and on the vessels6.php page this...
<?php
// Basic oci_connect() database connection
connection here
$return_arr = array();
$term = strtoupper(trim(strip_tags($_GET['term'])));//retrieve the search term that autocomplete sends
$sql = oci_parse($conn,"SELECT FIELD1, FIELD2, FROM TABLE1 WHERE MAX_DATE_CANCELED >= TRUNC(sysdate) and (FIELD1 LIKE '%$term%' OR FIELD2 LIKE '%$term%') ");
oci_execute($sql, OCI_DEFAULT);
while ($row = oci_fetch_array($sql, OCI_ASSOC+OCI_RETURN_NULLS)) {
$row_array["label"] = $row['FIELD1'] . ' - ' . $row['FIELD2'];
$row_array["value"] = $row['FIELD1'];
$row_array['FIELD2'] = $row['FIELD2'];
array_push( $return_arr, $row_array );
}
oci_close($conn);
// Truncate, encode and return the results
$return_arr = array_slice($return_arr, 0, 8);
echo json_encode($return_arr),"\n";
?>
I am using jQuery UI Autocomplete and I choose a selection in 1 text inout and want another input field to populate...
Related
Good afternoon, I’m trying jQuery ajax autocomplete for the first time and it seems to be working great but I have found my self in a bit of problem, you see I have a sql table name
Clients: with the following columns, id_client , clinent_name , id_user,
Basically each table is assigned to a user . and that’s where my problem comes
in index.php I have the following code :
<script type="text/javascript">
$(function() {
$("#name").autocomplete({
source: "/cliente.php",
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$('#client_name').val(ui.item.client_name);
$('#id_client').val(ui.item.id_cliente); })});
</script>
Which sends the value of the input with the name =’name’ to cliente.php
if (isset($_GET['term'])){
include 'include/conexion.php';
$return_arr = array();
if ($con)
{
$fetch = mysqli_query($con,"SELECT * FROM cliente where name like '%" .
mysqli_real_escape_string($con,($_GET['term'])) . "%' LIMIT 0 ,50");
while ($row = mysqli_fetch_array($fetch)) {
$id_cliente=$row['id_cliente'];
$row_array['value'] = $row['id_client']." | ".$row['cliente_name']; a
rray_push($return_arr,$row_array); }} mysqli_close($con); echo json_encode($return_arr);}
But the problem is I’m trying to send another value to cliente.php which is id_user so the user could only look up clients assign to them.
In PHP. we have to change the row array.
$row_array['value'] = $row['id_client']." | ".$row['cliente_name']; =>
$row_array[] = $row['id_client']." | ".$row['cliente_name'];
In js, we have to parse the return value. Label and value are the same in autocomplete success callback.
select: function(event, ui) {
event.preventDefault();
var values= ui.item.value.split("|");
if (values.length > 1) {
$('#client_name').val(values[1]);
$('#id_client').val(values[0]);
}
}
So I have this problem where I want to display multiple values to multiple input boxes depending on how many the value is. I have already a code but the problem is it is only displaying the value in one input box. I will show you the code.
Here is the database:
attId attSubject attDate docId
------ ----------------- ---------- ------
1 FAAS FRONT & BACK 2018-01-25 36
2 NOA & TAX BILL 2018-09-12 36
HTML code:
<input type="text" id="attchecklist" name="attchecklist">
Javascript code:
$("#num").val(mydata.docId);
var docIdChecklist = $("#num").val();
$("#attchecklist").load('php/getAttachmentForChecklist.php',
{docIdChecklist:docIdChecklist},
function(data) {
$("#attchecklist").val(data);
}
);
PHP code:
<?php
require_once('../kclass/kconnect.php');
require_once('../common.php');
session_name(xevPRJ);
session_start();
$response= new kconnect();
$response->DB = $_SESSION['sys'];
$docIdChecklist = $_POST['docIdChecklist'];
$response->setCon();
$sqlx = "SELECT attSubject from `attachment` WHERE ((docId = '$docIdChecklist') AND (is_deleted = 0))";
$resultx=$response->kMysqli->query($sqlx);
while($row=mysqli_fetch_array($resultx, MYSQL_ASSOC)){
$attSubject = $row['attSubject'];
echo $attSubject;
}
$response->unsetCon();
?>
and here is the result:
I want the result to be separated in input boxes. How to achieve this?
Assuming your div something like this
<div id="myDiv></div>
Then you can append your form using JS
...
$("#attchecklist").load('php/getAttachmentForChecklist.php',
{docIdChecklist:docIdChecklist},
function(data) {
data = JSON.parse(data);
$.each(data, function(index, value) {
$("#myDiv").append(`<input type="text" id="attchecklist${index}" name="attchecklist${index}" value="${value}">`)
});
}
);
However, you are expected to return JSON array of data, instead of just echo the data on PHP API. Something like this:
$result = [];
while($row=mysqli_fetch_array($resultx, MYSQL_ASSOC)){
array_push($result, $row['attSubject']);
}
$response->unsetCon();
echo json_encode($result);
So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers
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 have a form that has a dropdown selection menu that loads invoice ids from my database. I'm trying to prefill my form based on the value of the invoice selected from the drop down menu. In my database is a column "invoiceidcopy" which contains a value(s) that shows as a selection(s) for my drop down menu. If you notice in my image of my database table below you will notice the first row/record's invoiceidcopy field is blank..in my drop down menu ...of course...the first selection is blank. Ultimately my code below im trying to get to prefill my form works only when i select the blank selection from the drop down menu but not for the other 2 selections? How can I prefill my form based on a dropdown menu selection value?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){
var invoiceidcopy = $('#dropdown-select').val();
e.preventDefault();
$.ajax({
url: "/tst/orders2.php",
data: {
invoiceidcopy: invoiceidcopy
}
}).done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['invoiceidcopy']))
{
$invoiceidcopy= $_GET['invoiceidcopy'];
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".($invoiceidcopy)."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die();
}
}
?>
it seems the source of your error is from the json data you are sending to php via ajax. you should try enclosing the data key in quotes so that javascript will not replace it with the variable value.
data: {
'invoiceidcopy': invoiceidcopy
}
Another possible source of your error is the sql to select the records from the table.
Have you tried removing the brackets from the variable name like so
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = '".$invoiceidcopy."'";
or even using braces like
$query = "SELECT txt1, txt2, q1
FROM seguin_orders
WHERE invoiceidcopy = {$invoiceidcopy}";
Also it will be good to check the value before it is sent to php just to be sure it is what you expect. For example you can do something like:
e.preventDefault();
var invoiceidcopy = $('#dropdown-select').val();
alert(invoiceidcopy); /*display the value to confirm it is correct */
// use the javascript console
console.log(invoiceidcopy);