I have implemented on my site the jQuery autocomplete function which works well. However, I would like to use the result from the autocomplete to retrieve the selected person's telephone number from the database.
The database structure is this;
id | name | type | tel | mobile | email | level
===============================================
1 | John Smith | judge | 01234 567890 | 07812 345678 | jsmith#example.com | BS Two Star
Here is my updated code so far
Autocomplete function
<script>
jQuery(document).ready(function($) {
$('#inputChiefJudge').autocomplete({
source:'lookups/shows-sj-searchforjudge.php',
change: function (event, ui) {
$.ajax({
type: POST,
url: 'lookups/shows-sj-findtel.php',
data: 'id='+ id,
success: function(data) {
details = $.parseJSON(data);
$('#inputChiefJudge').text("hello");
$('#chiefjudgetel').text(details);
},
});
},
minLength:2});
});
</script>
lookups/shows-sj-findtel.php
<?php
include("config.php");
mysql_connect ($DbHost, $DbUser, $DbPass);
mysql_select_db ("equilive_manager");
$id = $POST["id"];
$result = mysql_query("SELECT tel, mob FROM officials WHERE id='{$id}'");
$judgerow = mysql_fetch_array($result, MYSQL_ASSOC);
$contactdetails[] = array(
'tel' => $row['tel'],
'mob' => $row['mob'],
);
echo json_encode($data);
flush();
?>
lookups/shows-sj-searchforjudge.php
<?php
// if the 'term' variable is not sent with the request, exit
if ( !isset($_REQUEST['term']) ) exit;
// connect to the database server and select the appropriate database for use
include("../config.php");
mysql_connect ($DbHost, $DbUser, $DbPass) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("equilive_manager");
// query the database table for name that match 'term'
$term = mysql_real_escape_string($_REQUEST['term']);
$rs = mysql_query("SELECT id, name, level FROM officials WHERE name LIKE '%{$term}%' ORDER BY name LIMIT 0,10");
// loop through each name returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['name'] .', '. $row['level'],
'value' => $row['name'],
'id' => $row['id'],
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
Thanks in advance,
Craig
You have one issue at least in the code, which is that in getChiefJudgeContactDetails() you're mixing javascript with php. Mixing the two works fine if it's the first time you output a page and the code is on a PHP page. But if you're expecting the javascript to run PHP code every time a change event is triggered from the auto-complete, then that won't work.
Use the select event as others have stated, inside that, make a ajax request to a similar end point as your autocomplete but send it the value of your option (e.g. the ID value 2). Then use SQL in a PHP script to fetch the row for that id and return it as a json object. Parse the result and update UI in the jquery ajax call result handler.
update:
Change your autocomplete to look like this
<script>
jQuery(document).ready(function($) {
$('#inputChiefJudge').autocomplete({
source:'lookups/shows-sj-searchforjudge.php',
select: function (event, ui) {
$.ajax({
type: POST,
url: 'lookups/shows-sj-findtel.php',
data: {id:id},
success: function(data) {
details = $.parseJSON(data);
$('#inputChiefJudge').text("hello");
$('#chiefjudgetel').text(details);
},
});
},
minLength:2});
});
</script>
Instead of using the change option of the autocomplete, use select (as stated by other answers to your question). Also, instead of using a string ("id="+id) as your data, use a js object ({id:id}). jquery will handle serializing it correctly before sending to the server, the result being that it actually shows up as a post variable in your php script.
Also, as more of a side note, I would suggest looking into using the PDO driver (http://www.php.net/manual/en/pdo.prepare.php) to access your database instead of using the mysql_* commands. It's object oriented and also automatically provides safety features that are not available in the old commands, such as prevention of SQL injection attacks.
You can do it in select option of autoComplete.
All you need to do is send new ajax request to get selected person number.
select: function (event, ui)
{
//make $.ajax request and send selected value.
//you can send selected value using => ui.item.value
}
You should use the "select" event of the autocomplete:
http://api.jqueryui.com/autocomplete/#event-select
Related
I am newbie to php and mysql. Using Cordova plugin for visual studio 2015 i have created a simple mobile application in which a user selects a serial number and on selecting it data is showed on the chart. Also there is a toggle switch button through which i can change the state of the switch from on-off or off-on. While changing the state the data is inserted into DB.
Now, i want is to do is that whenever i select a serial number the last state of the toggle should be shown on the switch. Means if the user has previously change the state from on to off for a particular serial number than this change should be shown if the same serial number is selected again.
For this i have done the following
My PHP CODE
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = isset($_REQUEST['Command_Name'])?$_REQUEST['Command_Name']:"";
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
//print_r($result);
echo json_encode( (array) $result->fetch_object());
mysqli_close($con);
echo $cmd_Name;
My html(ajax) code
$.ajax({
method: "GET",
url: "http://localhost:Port/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = $.parseJSON(JSON.stringify(data));
console.log(dt);
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
} else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function () {
toastr.success('Data not fetched', '', { timeOut: 2000 })
}
});
Now whenever i run the app this part of code executes and it always goes to the else part. i.e if my serial number's last state is On it shows me off as shown in the below image
In above image you can clearly see that the command_Name = on but still it goes to else part.
I must be doing something wrong, and that i don't know.
Any help would be highly appreciated.
I am having nearly 80,000 records in a single table in MYSQL, I wanna make it display in the Autocomplete control.
The table structure is given below
Table_name
-ID
-Code
-codeType
In client side, I have made that autocomplete script like given below
var Cds = "";
$.ajax({
type: "POST",
url:"cdList.php",
async: false,
data:{
value1 : '9'
},
success:function(result){
Cds = JSON.parse(result);
}
});
$("#prin").autocomplete({
minlength : 3,
source: Cds,
autoFocus:true,
width:500
});
cdList.php
<?php
$con = mysql_connect("localhost","***","***");
if(!$con){
die("Error : ".mysql_error());
}
mysql_select_db("ananth",$con);
$value1 = $_POST['value1'];
$cd9 = array();
$result = mysql_query("select * from Table_name where codeType = '9' AND Code LIKE '$value1%'");
while($row = mysql_fetch_array($result)){
$cd9[] = $row['Code'];
}
echo json_encode($cd9);
?>
Even i set minLength in autocomplete control, still i am feeling damn slowness on getting the data. It took around 30 seconds. So what will be the work around to make it fast?
Look at this post abot like operator.
For your case i reccomend using query_caching flag and select only one column instead *
select Code from Table_name where codeType = '9' AND Code LIKE '$value1%'
LIKE queries have a potential for taking a long time...
for autocomplete purposes you could use MySQL's LIMIT and return only a chunk of the relevant entries.
check out this link:
http://www.w3schools.com/php/php_mysql_select_limit.asp
also you should probably index codeType column for a faster search.
hope this helps
I am trying to access some info in my database and displaying the result of my query in some textboxes.. my code works but it says object object..
here's my jQuery code:
jQuery('body').on('click', '.update_button', function() {
var manufacturer_part = jQuery(this).val();
jQuery.ajax({
url: '/codes/clearhouse_processor.php',
type: 'POST',
data: {update_key: manufacturer_part},
dataType: 'json',
success: function(result) {
jQuery('#update-manufacturer-part').val(result.part_number);
jQuery('#update-manufacturer').val(result.manufacturer);
jQuery('.update-form').stop();
jQuery('.update-form').slideToggle('slow');
jQuery('html,body').animate({
scrollTop: jQuery('.update-form').offset().top-60
}, 750);
}
});
});
and here's my php code...
if(isset($_POST['update_key'])){
$manufacturer_part = $_POST['update_key'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('part_number')));
$query->from($db->quoteName('clearing_house'));
$query->where($db->quoteName('part_number') . '='.preg_replace("/[^0-9,.]/", "", #$manufacturer_part) );
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo json_encode($results);
}
and btw, I am using joomla here...
thanks in advance,
jQuery('#update-manufacturer-part').val(result[0].part_number);
it is receiving an array from the server
by the result you gave
and if you want to see all the results that you receive
jQuery('#update-manufacturer-part').val(result[0].part_number);
_.map(result,function(){return part_number; }).join(",")
on the query itself update the fields that you need to get
$query->select($db->quoteName(array('part_number', 'manufacturer', 'field3', 'fieild4')));
I am trying to return data from a database and convert it into json and send it back to my javascript. However its not working as planned, it returns as an array on the javascript.
Javascript
function getData(id) {
$.ajax({
url: 'some url',
crossDomain: true,
type: 'post',
data: {
id: id
},
success: function (data) {
var json = jQuery.parseJSON(data);
alert(data);
},
});
};
PHP
<?php
header("access-control-allow-origin: *");
$dbhost = 'you dont need this info';
$dbuser = 'you dont need this info';
$dbpass = 'you dont need this info';
$db = 'you dont need this info';
$dbserver = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db) or die("Unable to select database: " . mysql_error());
if (isset($_POST['id'])) {
$ID = $_POST['id'];
}
echo $ID;
$result = mysql_query('SELECT * FROM clubmember WHERE clubID = "' . $ID . '"');
$row = mysql_fetch_assoc($result);
$name = $row['name'];
$clubID = $row['clubID'];
$lID = $row['lID'];
$sName = $row['sName'];
$desc = $row['description'];
$json = json_encode(array(
'name' => $name,
'clubID' => $clubID,
'lID' => $lID,
'sName' => $sName,
'description' => $desc
));
echo $json;
?>
The javascript alerts in the form of [object Object], [object Object] ...
Which shouldn't be the case...
Don't echo $ID in your PHP. Use jQuery's ajax dataType property and set it to json. Use default javascript json parser.
try alerting json rather than data?
Javascript returns an object because you are in fact alerting an object. Try alert(data.name);
or alert(data.clubID);, it will work.
You should specify the data type that the ajax call is requesting, otherwise jQuery will "intelligently" detect based on the MIME type. If the ajax call receives json data, it will use it as a JavaScript object, which is why you are getting that alert.
That is right.
The JSON is an object. a.k.a Javascript Object Notation. That should be in case.
It should contain your data. Try data.*.
By the way, if you don't clear the data coming from your users before using it with any SQL Query, that will cause trouble.
See it in action with a basic example:
// $_POST['id'] = '" OR 1"'
$result = mysql_query('SELECT * FROM clubmember WHERE clubID = "'.$ID.'"');
Your query is now
SELECT * FROM clubmember WHERE clubID ="" OR 1 ""
Because 1 is always true, I am now able to take all of your clubmember table. Cheers.
Even if parseJSON returns an object, doing a console.log should show [Object, Object, ...] which is an array of object
The .ajax() call will, if the dataType parameter is not given, "intelligently guess" what the requested page returns. In the case of JSON, it will pass a JavaScript object to the success function.
After reviewing your question(s), I believe I get what you mean.
What you're expecting is a single object (looked up with SQL, as mentioned in a very insecure way) with 5 properties, name, clubID, lID, sName and description.
However, it seems that what you're getting back are multiple rows with only two properties?
What you're saying is that while the php script echo's the right values (one row) but JSON is receiving multiple values(/rows). Are you sure the PHP is receiving the right ID from the AJAX call?
I am using a jQuery/JS/Ajax script to dynamically fill SELECT boxes from my database, with each subsequent SELECT box being populated based on the the previous SELECT.
Eg. Someone selects 'England' from my first SELECT, this then populates the next SELECT with towns in England etc.
The trouble I'm having is getting the second SELECT function to recognise a variable. It's a lot of code so I don't want to paste it all but... this is the first function which populates the first SELECT box on page load:
function getTierOne()
{
$tblname = $_SESSION['country'];
$result = mysql_query("SELECT DISTINCT county FROM $tblname ORDER BY county")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
echo '<option value="'.$tier['county'].'">'.$tier['county'].'</option>';
}
}
This is fine, $tblname is a posted $_SESSION variable containing the users country, obvs.
The problem is 'onBlur' of this first SELECT box, a second SELECT box is brought up using this JS function and PHP call:
$(document).ready(function()
{
$('#wait_1').hide();
$('#drop_1').change(function()
{
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php",
{
func: "drop_1",
drop_var: $('#drop_1').val()
},
function(response)
{
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
});
});
...
if (isset($_GET['func'])&& $_GET['func'] == "drop_1") {
drop_1($_GET['drop_var']);
}
Which calls this function:
function drop_1($drop_var)
{
include_once('functions.php');
$result = mysql_query("SELECT DISTINCT town FROM $tblname WHERE county='$drop_var'")
or die(mysql_error());
echo '<select name="drop_2" id="drop_2">
<option value=" " disabled="disabled" selected="selected">Select Your Town/Nearest Town</option>';
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_2['town'].'">'.$drop_2['town'].'</option>';
}
echo '</select>';
echo '<input type="submit" name="submit" value="Continue" />';
}
But this function will not recognise my $tblname variable, even if i use Global! The only variable it recognises is $drop_var, which is the result of the first SELECT box.
Does anyone have any idea how i can pass the $tblname variable into
function drop_1($drop_var) { ...
If you're using PHP sessions to store the user's country (and from line1 of getTierOne() it looks like you are), you should be able to add the line to the start of your drop1() PHP function:
function drop_1($drop_var)
{
$tblname = $_SESSION['country'];
include_once('functions.php');
...
Jquery should be sending your user's cookie along with the GET parameters (func and dropvar), which allows PHP to know which session belongs to the user, and give them their session variables back (You can check this with the "Network" tab of Firebug / Chrome inspector- look for the call to func.php after onBlur has fired and look for the "Cookie" request header).
Alternatively, if you're not using sessions, but you have the country stored on the client-side (eg. as the first "drop_0" select box?), you could have jquery pass the selections from tier1 (county) select boxes in the get call. ie.
$.get("func.php",
{
func: "drop_1",
country: "VALUE OF COUNTRY HERE",
drop_var: $('#drop_1').val()
},
function(response)
{ ...
And modify your server-side PHP code to accept 2 arguments instead of one.
From a maintainability point of view, consider not using multiple tables (one per country) and instead use a single table with an additional "country" column. It's rarely a good idea to have multiple identically structured tables, MySQL generally handles millions of rows much better than hundreds of tables, and it makes joins and making changes to your tables' structure more difficult.
You also should be sanitizing the inputs, not using $GET['drop_var'] directly in a SQL query, or it'll break on quotes and opens you up to SQL injection attacks. (Apologies if you have a good reason for doing either of these: Obviously you know more about your specific requirements than I do!)