Actually, I have done location search for normal HTML input type in my site (not functionality wise), I have stored locations name in database, if I search any location it should come jQuery autocomplete also and if I click a bangalore means bangalore records will open, fetching from database how will fix and please help me anyone.
Here my HTML markup:
<div class="form-group keyword">
<input type="text" id="location" placeholder="Search by location" name="location" list="locations" class="searchlocation" />
</div>
Here my PHP code:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `pg_address` FROM `tbl_master_property` WHERE pg_address LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
$data[] = $row['pg_address'];
}
echo json_encode($data);
?>
Ajax and jQuery code:
<script type="text/javascript">
$(function() {
$( "#location" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "locationsearch.php",
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
});
});
</script>
Related
I have autocomplete jQuery script working for pulling suggestions from MySQL database when typing in form fields on the page (3 input fields).
That is working fine, but what I would like is to when I select suggested option in the first field - all 3 fields should be filled.
Fields that I have right now is first name, last name, and company. When I select the first name - last name and company should be automatically filled with data.
Here's php:
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function()
{
$( "#first_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#last_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#company" ).autocomplete({
source: 'autocomplete.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="ui-widget">
<p>First name</p>
<input type="text" id="first_name">
</div>
<div class="ui-widget">
<p>Last name</p>
<input type="text" id="last_name">
</div>
<div class="ui-widget">
<p>Company</p>
<input type="text" id="company">
</div>
</div>
</body>
</html>
And here's the autocomplete.php file:
<?php
$host="localhost";
$username="user";
$password="password";
$databasename="dbname";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$searchTerm = $_GET['term'];
$select =mysql_query("SELECT * FROM jemployee WHERE first_name LIKE '%".$searchTerm."%'");
while ($row=mysql_fetch_array($select))
{
$spojeno = $row['first_name'] . ' ' . $row['last_name'] . ' ' . $row['kompanija'];
$data[] = $spojeno;
}
//return json data
echo json_encode($data);
?>
So, when the suggested option from "first_name" is selected - "last_name" and "company" should be filled with corresponding data from a database. Any suggestions?
Use something Jquery likes:
$(document).on('keyup', '#firstname', funtion(){
$.ajax({
type:"POST",
url:"ajax.php",
data:$("#firstname").val();
},
success:function (res){
$("#lastname").val(res.lastname);
$("#company").val(res.company);
},
)};
});
And PHP ajax.php file:
<?php
\\Select lastname, company with $_POST['data']
echo json_endcode($result);
Should check and handle the ajax response. If you can you this solution, please make it better.
What I did is passing the ajax "item" result as the autocomplete "value" :
It looks like this :
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id, //the data that will be shown in the list !
value: item //item holds "Id" and "Name" properties
};
}))
}
I then subscribe the autoComplete "select" event to prevent it's default behaviour.
I then fill the different fields I need to :
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
here's the entire autocomplete call, in case it helps ;)
$("#CustomerId").autocomplete({
source: function (request, response) {
$.ajax({
url: "/.../../GetAvailablePartnerInformations",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id,
value: item
};
}))
}
})
},
change: function (event, ui) {
//Forces input to source values, otherwise, clears
//NOTE : user could still submit right after typing => check server side
if (!ui.item) {
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$(event.target).val("");
$(event.target).addClass("is-invalid");
}
else {
$(event.target).removeClass("is-invalid");
}
},
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
//Note : the "value" object is created dynamically in the autocomplete' source Ajax' success function (see above)
debugger;
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
messages: {
noResults: "",
results: function (resultsCount) { }
},
autoFocus: true,
minLength: 0
})
I have a record of carriers and clients. When selecting a carrier on the customer screen, I need it to be automatically filled out the carrier's e-mail and telephone. The PHP file is returning a JSON correctly, but it is dropping in the error of jquery and not in success. I checked in Firefox's Firebug and the HTML tab of the console, where the GET requisition is reset.
<?php
include "Config/config_sistema.php";
$res = mysql_query("SELECT * FROM transportadoras");
$menu_items = null;
while($ln = mysql_fetch_object($res)){
$menu_items[] = $ln;
}
json_encode($menu_items);
?>
<script>
$("body").on("change","#transportadoras",function(event){
event.preventDefault();
var trigger=$(this);
$.ajax ({
type: "POST",
url: "buscaDadosTransportadora.php",
dataType: 'json',
success: function (data) {
$("#telefone_transp").val(data.telefone);
$("#email_transp").val(data.email);
},
error: function (data) {
alert("Erro");
},
});
});
</script>
return in ajax
[{"ID":"5","Nome":"Vinicius","email":"viniciusbalbinot91#gmail.com","telefone":"32680018"},{"ID":"6","Nome":"teste","email":"teste#teste.com.br","telefone":"12345567"}]
You response is array .
[{"ID":"5","Nome":"Vinicius","email":"viniciusbalbinot91#gmail.com","telefone":"32680018"},....]
you should loop through data.
success: function (data) {
$.each(data,function(user){ /* code ...*/});
}
If you want some current row select one row from mysql .
hope it can help u
php.php
$inp=$_POST["data"];
$txt[0]=array("ID"=>"5","Nome"=>"Vinicius","email"=>"viniciusbalbinot91#gmail.com","telefone"=>"32680018");
$txt[1]=array("ID"=>"6","Nome"=>"teste","email"=>"teste#teste.com.br","telefone"=>"12345567");
for($c=0;$c<sizeof($txt);$c++)
{
if($txt[$c]["ID"]==$inp)
{echo json_encode($txt[$c]);}
}
index.php
ID:<input id="txt" name="txt" type="text" />
<br><br>
Name:<input id="name" name="txt0" type="text" disabled="disabled"/><br>
Email:<input id="email" name="txt0" type="text" disabled="disabled"/><br>
Tel:<input id="tel" name="txt0" type="text" disabled="disabled"/><br>
js
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("document").ready(function()
{
$("#txt").keyup(function ()
{
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{data : $("#txt").val()},
success: function(data)
{
$("#name").val(data.Nome);
$("#email").val(data.email);
$("#tel").val(data.telefone);
},
error: function ()
{
alert("Error!");
}
});
});
});
</script>
Please help me how to submit form (comments) without page refresh for
HTML markup:
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="submit" id="comq"name="compost" class="butn2">post comment</button>
</form>
PHP code (pnf.php):
if(isset($_POST["compost"]))
{
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
jQuery and Ajax:
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
I have tried many times and don't know what mistake I made, Ajax and jQuery are not working, please anyone help - thanks in advance
You have made couple of mistakes.
First:: You should put button type="button" in your HTML form code
Second:: You have made a syntax error. $("#comment").vol(); should be replaced with $("#comment").val(); in your jQuery AJAX
As you mentioned that you have to send request without refreshing page I modified your JS-code with preventing default submitting form:
$(document).ready(function () {
$("#commentf").submit(function (e) {
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
type: "POST",
url: "pnf.php",
data: {
"done": 1,
"comments": comment
},
success: function (data) {
}
})
});
});
Javascript
$('form').on('submit', function(event){
event.preventDefault();
event.stopPropagination();
var dataSet = {
comment: $('#comment').val();
}
$.ajax({
url: "link.to.your.api/action=compost",
data: dataSet,
method: 'post',
success: function(data){
console.log('request in success');
console.log(data);
},
error: function(jqXHR) {
console.error('request in error');
console.log(jqXHR.responseText');
}
});
});
PHP
$action = filter_input(INPUT_GET, 'action');
swicht($action){
case 'compost':
$comment = filter_input(INPUT_POST, 'comment');
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if(!$stmt)
{
http_response_code(400);
echo 'internal error';
}
echo 'your data will be saved';
break;
default:
http_response_code(404);
echo 'unknown action';
}
you have to prevent the submit on the form (look in javascript).
after that you send the request to the server and wait for success or error.
in php try to do it with a switch case. and try to not touch super globals directly, use filter_input function.
hope this helps
Modified JQuery Code...
$( document ).ready(function() {
console.log( "ready!" );
$("#comq").click(function() {
var comment=$("#comment").val();
console.log('comment : '+comment);
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
HTML Code
<form id="commentf" method="post">
<textarea class="textinput" id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<input type="button" id="comq" name="compost" class="butn2" value="Post Comment">
</form> </div>
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="button" id="comq"name="compost" class="butn2">post comment</button>
</form>
script
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
PHP code (pnf.php):
comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
if you are using jquery make sure to include jquery libraries before your script file.
latest jquery cdn minified version
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
example
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="yourjsfile.js" type="text/javascript"></script>
I'm new in bootstrap and i need some help please, i want to create a typeahead drop-down that return 3 values from my mysql database when the user search for a contact name in "ContactName" TEXTBOX and fill up 3 edit box with the information of
-contact name
-Telephone Number
-email address
thanks a lot on advance for all your effort
this is the code that i try it to return one value i need to modified to return all those tree value
Now when i try to search the contact name it will return with correctly with no question to ask but i don't know how to modify the code to bring 3 value like i mention above
enter code here
**php page: Customer.php**
-------------------------------------------
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "db34218";
$connection=mysql_connect($host,$uname,$pass) or die("connection in not ready <br>");
$result=mysql_select_db($database) or die("database cannot be selected <br>");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT ContactName, Telephone, Email FROM customer WHERE ContactName LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['ContactName'];
}
echo json_encode ($array); //Return the JSON Array
}
?>
**html and java page and some php: Customersearch.php**
------------------------------------------------
<body>
.
.
.
<div class="row-fluid">
<div class="span4">
<label>ContactName </label>
<input type="text" name="ContactName" value="<?php echo $row_Recordset_QuoteCustomer['ContactName']?>" data-provide="typeahead" class="typeahead input-xlarge" autocomplete="off">
</div>
<div class="span2">
<label>Telephone </label>
<input type="text" name="Telephone" value="<?php echo htmlentities($row_Recordset_QuoteCustomer['Telephone'], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
<div class="span2">
<label>Email </label>
<input type="text" name="Email " value="<?php echo htmlentities(row_Recordset_QuoteCustomer['Email '], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
.........
.
.
.
.
.
.
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap-transition.js"></script>
<script src="../js/bootstrap-alert.js"></script>
<script src="../js/bootstrap-modal.js"></script>
<script src="../js/bootstrap-dropdown.js"></script>
<script src="../js/bootstrap-scrollspy.js"></script>
<script src="../js/bootstrap-tab.js"></script>
<script src="../js/bootstrap-tooltip.js"></script>
<script src="../js/bootstrap-popover.js"></script>
<script src="../js/bootstrap-button.js"></script>
<script src="../js/bootstrap-typeahead.js"></script>
<script src="../js/SpecWorkPages/getItemsList.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('input.typeahead').typeahead({
source: function (query, process)
{
$.ajax(
{
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data)
{
console.log(data);
process(data);
}
});
}
});
})
</script>
</body>
</html>
<?php
mysql_free_result($RecordsetQuote);
mysql_free_result($Recordset_QuoteStatus);
mysql_free_result($Recordset_QuoteCustomer);
?>
If I'm understanding you correctly, you are getting results back but unable to populate the input fields. Although I don't use Twitter Bootstrap typeahead I do something very similar with jQuery's autocomplete feature. The code below is untested and of course you'll need to modify it for yourself but hopefully will be of some help.
See this working jsFiddle demo for something similar.
PHP
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
array_push($array,array('ContactName'=>$row['ContactName'],'Telephone'=>$row['Telephone'],'Email'=>$row['Email']));
}
echo json_encode($array);
You can check what gets returned by manually entering the URL (ex: yoursite/Customer.php?query=SomeContactName). You should see something similar to this:
[{"ContactName":"Some Contact","Telephone":"5555555555","Email":"email#whatever.com"},
{"ContactName":"Some Other Contact","Telephone":"5555555555","Email":"anotheremail#whatever.com"}]
HTML/Javascript
<script>
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
// data: 'query=' + query,
data: 'query=' + $('#contactName').val(),
success: function(data)
{
var results = data.map(function(item) {
var someItem = { contactname: item.ContactName, telephone: item.Telephone, email: item.Email };
return JSON.stringify(someItem.contactname);
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
// This may need some tweaks as it has not been tested
var obj = JSON.parse(item);
return item;
}
});
</script>
Here are a couple other posts that you might want to take a look at How to return the response from an AJAX call? and Bootstrap typeahead ajax result format - Example
I am trying to autocomplete a text box in my search.php code using autocomplete.php
I know that my php code works perfectly and echo's back exactly what is needed for the autocomplete function in jQuery.
Here is the html for the text box.
<input type="text" name='search' id="search" class="input-block-level" autocomplete="off" placeholder="search...">
Here is my script for the autocomplete function
<script>
jQuery(document).ready(function($){
$('#search').autocomplete({source:'autocomplete.php', minLength:2});
});
</script>
Here is the php file
<?php
if ( !isset($_GET['term']) )
exit;
$conn = odbc_connect('Abilis', 'infosysreader', 'Wilsons12');
$query = "SELECT TOP 10 [Del_ad1] FROM [Abilis].[dbo].[Customers] WHERE Del_ad1 LIKE '%".$_GET['term']."%'";
$rs = odbc_exec($conn, $query);
$data = array();
for($i = 0; $i<odbc_num_rows($rs);$i++){
$row = odbc_fetch_array($rs, $i);
$data[] = array(
'label' => $row['Del_ad1'],
'value' => $row['Del_ad1']
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
Edit:
I found my error at the end of my html file. It was just a mistake on my part, the method I use above works fine.
Not sure what your problem is but since your PHP correctly returns json encoded string then problem is with autocomplete call. Try this and let me know if it makes any difference:
$('#search').autocomplete({
minLength:2,
source: function(request, response) {
$.ajax({
url: 'autocomplete.php',
dataType: 'json',
data: { term : request.term },
success: function(result) {
response(result);
}
});
}
});
Also try changing autocomplete="off" to autocomplete="on"
Remove the following from input element:
class="input-block-level" autocomplete="off" placeholder="search..."
and try with <input type="text" name='search' id="search" />