I would like to use autocomplete to search for city and auto fill city name and city id text boxes. Looks simply, but even I pass thru many examples I am simply not able to make it work :(
My biggest success was code below but it makes two separate autocompletes.
HTML:
<form action="form_handler_event_add.php"
method="post"
name="form_event_add">
City: <input type="text" id="city" name="city" />
ID_City : <input type="text" id="id_city" name="id_city" />
</form>
Script:
<script type="text/javascript">
$(document).ready(function(){
$("#city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1
});
$("#id_city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1
});
});
</script>
handler_getautocomplete.php:
$query=mysql_query("SELECT * FROM cities WHERE city_name like '%".$term."%'");
$json=array();
while($city=mysql_fetch_array($query)){
$json[]=array(
'value'=> $city["city_name"],
'id'=>$city["id_city"]
);
}
echo json_encode($json);
So if you want to fill the #id_city input when the city is selected, use the select event:
PHP: handler_getautocomplete.php should return the json encoded string from an array in the following format:
$json = [
[ 'id' => 1, 'value' => 'New York' ],
[ 'id' => 2, 'value' => 'Alabama' ],
[ 'id' => 4, 'value' => 'Seatle' ],
[ 'id' => 6, 'value' => 'San Francisco' ]
];
JS:
$("#city").autocomplete({
source:'handler_getautocomplete.php',
minLength:1,
select: function( event, ui ) {
$( '#id_city' ).val( ui.item.id );
}
});
I think the problem is in the json encoding. In the php handler try this:
$query=mysql_query("SELECT * FROM cities WHERE city_name like '%".$term."%'");
$json=array();
while($city=mysql_fetch_array($query)){
$value[] = $city['city_name'];
$id[] = $city['city_id'];
}
$city_array = array('value' => json.encode(array_values($value)),
'id' => json.encode(array_values($id))
);
return $city_array;
I think is better to make it a function returning a two dimension arrays, wich you can store in a variable $cities.
In the javascript code you should do something like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#city").autocomplete({source: <?php echo $cities['value']; ?>, minLength: 1});
$("#id_city").autocomplete({source: <?php echo $cities['id']; ?>, minLength: 1});
</script>
The main problem is that json format is not valid for jquery autocomplete, print it so you can see the difference. Hope it can help you.
Finally manage it. Here is the final codes, maybe it will help to someone:
HTML:
City : <input type="text" id="city" name="city" />
ID_city : <input type="text" id="id_city" name="id_city" />
Script:
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source:'handler_getautocomplete.php',
select: function(event, ui) {
$('#id_city').val(ui.item.value);
event.preventDefault();
$("#city").val(ui.item.label); },
minLength:1
};
$("#city").autocomplete(ac_config);
});
</script>
PHP:
$term = trim(strip_tags($_GET['term']));
$query=mysql_query("SELECT city_name, id_city FROM cities WHERE city_name like '%".$term."%'");
$matches = array();
while($city=mysql_fetch_array($query) and $i<10){
$matches[]=array('value' => $city['id_city'],
'label' => $city['city_name'])
;}
print json_encode($matches);
Related
I've been working to add autocomplete to my Location text field, the problem is when I type any word on it, it always display all the result.
This is my javascript:
<script type="text/javascript">
$(function(){
$("#Location").autocomplete({
source: "{{ route('search.autocomplete') }}",
minLength: 3,
select: function(event, ui){
$("#Location").val(ui.item.value);
}
});
});
</script>
This is the route.php
Route::get('search/autocomplete', ['uses' => 'SearchController#autocomplete', 'as' => 'search.autocomplete']);
This is the searchController
public function autocomplete(Request $request){
$term = $request->get('Location');
$provinces = DB::table('provinces')->where('ProvinceName', 'LIKE', '%'. $term .'%')
->orderBy('ProvinceName', 'desc')
->get();
$results = [];
foreach ($provinces as $province) {
$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
}
return response()->json($results);
}
and this is the search.blade.php
<div class="form-group col-md-4">
Location: {!!Form::text('Location', Request::get('Location'), ['class' => 'form-control', 'placeholder' => 'What is your location?', 'id' => 'Location', 'style' => 'width: 250px;'])!!}
</div>
Okay I solve my problem, I change
route.php
Route::get('search/autocomplete', 'SearchController#autocomplete');
SearchController
if ($request->ajax()) {
$term = Input::get('term');
$results = array();
$queries = DB::table('provinces')
->where('ProvinceName', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->ProvinceName ];
}
return Response::json($results);
}
and my Javascript
<script type="text/javascript">
$(function()
{
$( "#Location" ).autocomplete({
source: "{{ url('search/autocomplete') }}",
minLength: 3,
select: function(event, ui) {
$('#Location').val(ui.item.value);
}
});
});
</script>
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
Change
$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
to
$results[] = ['value' => $province->id, 'label' => $province->ProvinceName];
And
$("#Location").val(ui.item.value);
To
$("#Location").val(ui.item.label);
Use id in frontend as
ui.item.value
views.php
<div class="input-group">
<input class="form-control" id="nomor_cari" maxlength="16" placeholder="No. CM / No. KTP">
script autocomplete
$('#nomor_cari').autocomplete({
source: get_no,
dataType: 'JSON'
});
function get_no
<?php
function get_no($q)
{
$this->db->select('NO_MEDREC');
$this->db->like('NO_MEDREC', $q);
$query = $this->db->get('PASIEN_IRJ');
if($query->num_rows > 0)
{
foreach ($query->result_array() as $row)
{
$row_set[] = htmlentities(ucfirst($row['NO_MEDREC']));
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($row_set));
}
echo $query->row();
}?>
but autocomplete didn't show anything.
if i use local variable , autocomplete works like it should be.
<script> var availableNumber = [
"0000000002",
"0000000020",
"0000000200",
"0000002000"
];
/<script>
and changes autocomplete to
$('#nomor_cari').autocomplete({
source: availableNumber,
dataType: 'JSON'
});
what did i missed? (im sure .js are loaded because when using local var , it works like charm)
just in case needed , here's my autoload
$autoload['libraries'] = array('database', 'email', 'session');
$autoload['helper'] = array('url', 'template', 'message', 'misc');
I think issue is in "source". Please try to use json like this
$('#nomor_cari').autocomplete({
source: function (request, response) {
$.getJSON("ful_url/get_no?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
});
So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();
i have a form with two select box. one is for the city and the other one for the area.
My requirement. When some one selects a city,The areas in the city must be captured from database and displayed in another select box.
i tried but, i have problem with my ajax. here is my code below.
view
<div class="location-group">
<label class="-label" for="city">
Location
</label>
<div class="">
<select id="city_select">
<option value="0"> select</option>
<?php foreach ($city as $cty) : ?>
<option value="<?php echo $cty->city_id; ?>"><?php echo $cty->name; ?></option>
<?php endforeach ?>
</select>
</div>
</div>
<div class="location control-group" id="area_section">
<label class="control-label" for="area">
Area
</label>
<div class="controls">
<select id="area_select">
<option value=""> Any</option>
<?php foreach ($area as $ara) : ?>
<option value="<?php echo $ara->ara_id; ?>"><?php echo $ara->name; ?></option>
<?php endforeach ?>
</select>
</div><!-- /.controls -->
</div><!-- /.control-group -->
controller
function __construct() {
parent::__construct();
//session, url, satabase is set in auto load in the config
$this->load->model('Home_model', 'home');
$this->load->library('pagination');
}
function index(){
$data['city'] = $this->home->get_city_list();
$data['type'] = $this->home->get_property_type_list();
$this->load->view('home', $data);
}
function get_area(){
$area_id = $this->uri->segment(3);
$areas = $this->home->get_area_list($area_id);
echo json_encode($areas);
}
Model
function get_area_list($id){
$array = array('city_id' => $id, 'status' => 1);
$this->db->select('area_id, city_id, name');
$this->db->where($array);
$this->db->order_by("name", "asc");
$this->db->from('area');
$query = $this->db->get();
$result = $query->result();
return $result;
}
Ajax
<script type="text/javascript">
$('#area_section').hide();
$('#city_select').on('change', function() {
// alert( this.value ); // or $(this).val()
if (this.value == 0) {
$('#area_section').hide(600);
}else{
//$("#area_select").html(data);
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('index.php?/home/get_area/') ?>",
data: {area:data},
success: function(data) {
$('select#area_select').html('');
$.each(data, function(item) {
$("<option />").val(item.area_id)
.text(item.name)
.appendTo($('select#area_select'));
});
}
});
$('#area_section').show(600);
};
});
</script>
once i select a city, it must get all the areas in the city from database and display it in the area_select select box.
can any one please help me. Thanks.
Try to change this way.
Your ajax code
//keep rest of the code
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('index.php?/home/get_area/') ?>",
data: {area:$(this).val()},//send the selected area value
Also show the area_section inside ajax success function
Your controller function
function get_area()
{
$area_id = $this->input->post('area');
$areas = $this->home->get_area_list($area_id);
echo json_encode($areas);
}
Hope it will solve your problem
Update
Try using your ajax update function like this
success: function(data) {
$('select#area_select').html('');
for(var i=0;i<data.length;i++)
{
$("<option />").val(data[i].area_id)
.text(data[i].name)
.appendTo($('select#area_select'));
}
}
Simple way to do that follow the instruction on this page
https://itsolutionstuff.com/post/codeigniter-dynamic-dependent-dropdown-using-jquery-ajax-exampleexample.html
demo_state table:
CREATE TABLE `demo_state` (
`id` int(11) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
demo_cities table:
CREATE TABLE `demo_cities` (
`id` int(11) NOT NULL,
`state_id` int(12) NOT NULL,
`name` varchar(155) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password.
application/config/database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'test',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Read Also: How to make simple dependent dropdown using jquery ajax in Laravel 5?
Step 3: Add Route
In this step you have to add two new routes in our route file. We will manage layout and another route for ajax, so let's put route as bellow code:
application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['myform'] = 'HomeController';
$route['myform/ajax/(:any)'] = 'HomeController/myformAjax/$1';
Step 4: Create Controller
Ok, now first we have to create one new controller HomeController with index method. so create HomeController.php file in this path application/controllers/HomeController.php and put bellow code in this file:
application/controllers/HomeController.php
<?php
class HomeController extends CI_Controller {
/**
* Manage __construct
*
* #return Response
*/
public function __construct() {
parent::__construct();
$this->load->database();
}
/**
* Manage index
*
* #return Response
*/
public function index() {
$states = $this->db->get("demo_state")->result();
$this->load->view('myform', array('states' => $states ));
}
/**
* Manage uploadImage
*
* #return Response
*/
public function myformAjax($id) {
$result = $this->db->where("state_id",$id)->get("demo_cities")->result();
echo json_encode($result);
}
}
?>
Step 5: Create View Files
In this step, we will create myform.php view and here we will create form with two dropdown select box. We also write ajax code here:
application/views/myform.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Dependent Dropdown Example with demo</title>
<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Select State and get bellow Related City</div>
<div class="panel-body">
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
<?php
foreach ($states as $key => $value) {
echo "<option value='".$value->id."'>".$value->name."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" class="form-control" style="width:350px">
</select>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url:"<?php echo base_url('index.php/Diplome/myformAjax/') ?>"+ stateID,
//url: '/myform/ajax/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
</body>
</html>
I am trying to get Stripe's Checkout Custom Button to charge a credit card but all it does is minimize after I enter the credit card details. I am using the code found in the documentation but I can't get it to work. The simple button is easy to use and I figured it would be as easy as just customizing that one but it's very different.
Here's the code:
Payment Page
<form action="charge.php" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<input type="submit" value="Pay with card" id="customButton"/>
<?php require_once('./config.php'); ?>
<script>
var handler = StripeCheckout.configure({
key: '<?php echo $stripe['publishable_key']; ?>',
image: 'favicon.png',
token: function(token, args) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'Imprintnation',
description: 'Decals',
amount: <?php echo $stripeTotal; ?>
});
e.preventDefault();
});
</script>
</form>
Charge Page(charge.php)
<?php
require_once(dirname(__FILE__) . '/config.php');
$token = $_POST['stripeToken'];
$customer = Stripe_Customer::create(array(
'email' => 'customer#example.com',
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => 5000,
'currency' => 'usd'
));
echo '<h1>Successfully charged $5!</h1>';
?>
Configuration Page(config.php)
<?php
require_once('./lib/Stripe.php');
$stripe = array(
secret_key => 'sk_test_************************',
publishable_key => 'pk_test_************************'
);
Stripe::setApiKey($stripe['secret_key']);
?>
What am I missing here? I can't even get it to retrieve a token.
How can I retrieve a token and charge a card?
Finally got it to work. Had to change a bunch of it. Here is the code:
Payment page
<form action="charge.php" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<button id="customButton">Pay with Card</button>
<style>
#customButton{
width:300px;
height:50px;
background-color:orange;
color:white;
border:2px solid green;
}
</style>
<script>
$('#customButton').click(function(){
var token = function(res){
var $input = $('<input type=hidden name=stripeToken />').val(res.id);
$('form').append($input).submit();
};
StripeCheckout.open({
key: '<?php echo $stripe['publishable_key']; ?>',
address: false,
amount: '<?php echo $price; ?>',
currency: 'usd',
name: 'test',
description: '<?php echo $desc; ?>',
panelLabel: 'Checkout',
token: token
});
return false;
});
</script>
<input type="hidden" name="desc" value="<?php echo $desc; ?>"/>
<input type="hidden" name="totalPrice" value="<?php echo $price; ?>"/>
</form>
charge.php
<?php
require_once(dirname(__FILE__) . '/config.php');
$token = $_POST['stripeToken'];
$amount = $_POST['totalPrice'];
$desc = $_POST['desc'];
$percent = "0.01";
$realAmount = $amount * $percent;
try {
$charge = Stripe_Charge::create(array(
'card' => $token,
'amount' => $amount,
'currency' => 'usd',
'description' => $desc
));
} catch(Stripe_CardError $e) {
// The card has been declined
}
echo "<h1>Successfully charged $$realAmount!</h1>";
?>
I wish Stripe's documentation was more straightforward but this code handles the charge and it logs it on your dashboard.
#BlueSix is right, why do you have:
<input type="hidden" name="totalPrice" value="<?php echo $price; ?>"/>
Just because the value is hidden, does not mean it cannot be edited by the end user.
It would be much better to set $amount = $price directly, passing the variable through your application backend.