Ajax with select box in codeigniter - javascript

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>

Related

Issue with delete multiple orders - codeigniter 3

With this function I can correct delete single record:
` //delete order
public function delete_order($id)
{
$id = clean_number($id);
$order = $this->get_order($id);
if (!empty($order)) {
//delete order products
$order_products = $this->get_order_products($id);
if (!empty($order_products)) {
foreach ($order_products as $order_product) {
$this->db->where('id', $order_product->id);
$this->db->delete('order_products');
}
}
//delete invoice
$this->db->where('order_id', $order->id)->delete('invoices');
//delete order
$this->db->where('id', $id);
return $this->db->delete('orders');
}
return false;
}`
Now I try prepare function for delete multiple records.
In header table I add:
` <th scope="col" style="width: 25px;">
<div class="form-check">
<input class="form-check-input fs-15" type="checkbox" id="checkAll">
</div>
</th>`
and in foreach:
` <th scope="row">
<div class="form-check">
<input class="form-check-input fs-15" name="checkbox-table" type="checkbox" name="checkAll" value="<?php echo $item->id; ?>">
</div>
</th>`
Now I created action:
`<a class="dropdown-item" onclick="delete_selected_orders('<?php echo trans("confirm_products"); ?>');"><?php echo trans('delete'); ?></a>`
.js script
`<script>
//delete selected orders
function delete_selected_orders(message) {
swal({
text: message,
icon: "warning",
buttons: true,
buttons: [sweetalert_cancel, sweetalert_ok],
dangerMode: true,
}).then(function (willDelete) {
if (willDelete) {
var order_ids = [];
$("input[name='checkbox-table']:checked").each(function () {
order_ids.push(this.value);
});
var data = {
'order_ids': order_ids,
};
data[csfr_token_name] = $.cookie(csfr_cookie_name);
$.ajax({
type: "POST",
url: base_url + "order_admin_controller/delete_selected_orders",
data: data,
success: function (response) {
location.reload();
}
});
}
});
};
</script>`
order_admin_controller/delete_selected_orders
` /**
* Delete Selected Orders
*/
public function delete_selected_orders()
{
$order_ids = $this->input->post('order_ids', true);
$this->order_admin_model->delete_multi_orders($order_ids);
//reset cache
reset_cache_data_on_change();
}`
model
//delete multi order
public function delete_multi_orders($order_ids)
{
if (!empty($order_ids)) {
foreach ($order_ids as $id) {
$this->delete_order($id);
}
}
}`
When I check all and post delete multiple action then I see sweatalert to confirm delete, when I confirm I not see any error in console browser. But When I select multiple records and post then page refresh and orders not deleted.
I think function controller/model is correct. But im not sure with this in .js order_ids and in view table if I post order_ids correct.

How to execute two actions with one ajax call - WordPress

I have a section for "tours" in my page.
The tours have 2 filters (select inputs). "destino" and "duracion" (location and duration)
So far I made one of the filter work with ajax, and update the "#result" id with the new tours once you select a "destino".
But i also want to update the "duracion" select with the new options (based on the destino selected).
Problem is, i have no idea how to execute two actions and have the response on two different places.
Html part: (here I have both actions, its only executing the last one)
<form class="filtros righter" action="**********/wp-admin/admin-ajax.php" method="POST" id="filtro">
<input type="hidden" name="action" value="filtertoursajax">
<input type="hidden" name="action" value="filterduracionajax">
<input type="hidden" name="filtrodestino" value="salar-de-uyuni">
<div class="select-holder">
<label class="">Categoría</label>
<select name="categoriafilter" id="categoriafilter">
<option disabled="" selected="" value="0"> </option>
<option value="0">Todas las categorías</option>
<option value="11">Clásicos</option>
<option value="33">Elite</option>
</select>
</div>
<div class="select-holder">
<label>Duración del viaje</label>
<select name="duracionfilter" id="resultselect">
<option disabled="" selected="" value="0"> </option>
<option value="0">Todas las duraciones</option>
</select>
</div>
</form>
Js part:
<script>
jQuery(function myFunction(){
$('#filtro').change(function(){
var filter = $('#filtro');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr, data){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
console.log(data);
},
error: function(req, err){ console.log(err);
}
});
return false;
});
});
PHP action 1:
add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');
function filtertoursajax(){
$args = array(
'post_type' => 'tours',
'orderby' => 'menu_order',
'order' => 'ASC',
'post_per_page' => -1,
);
if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {
// for taxonomies / categoria
if( isset( $_POST['filtrodestino'] ) ) {
$args['tax_query'][] =
array(
'taxonomy' => 'destino',
'field' => 'slug',
'terms' => $_POST['filtrodestino']
);
}
}
if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {
// for taxonomies / categoria
$args['tax_query'][] =
array(
'taxonomy' => 'categoria',
'field' => 'id',
'terms' => $_POST['categoriafilter']
);
}
$query = new WP_Query( $args );
if( $query->have_posts() ) :
print_r($args);
while( $query->have_posts() ): $query->the_post();
$postid = $query->post->ID;
$taxonomy = 'destino';
$terms = get_the_terms( get_the_ID(), $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) :
$term_links = array();
foreach ( $terms as $term ) {
$term_links[] = '' . __( $term->name ) . '';
}
$all_terms = join( ', ', $term_links );
$destinos = '<span class="terms-' . esc_attr( $term->slug ) . '">' . __( $all_terms ) . '</span>';
endif;
?>
<div class="box">
<div class="box__image flexer">
<?php echo wp_get_attachment_image( get_field( "foto_portada", $postid ), array('276', '180'), "", array( "class" => "img-responsive" ) ); ?>
</div>
<div class="box__content pz-1">
<span class="placeholder mb-1"><?php echo $destinos; ?></span>
<h6 class="long-title mb-2"><?php echo $query->post->post_title; ?></h6>
<div class="icon-btn"><?php $path = get_template_directory_uri().'/images/plane-icon.svg'; echo file_get_contents($path); ?>Duración: <?php echo get_field( "duracion_texto", $postid ); ?></div>
</div>
Ver ficha<?php $path = get_template_directory_uri().'/images/arrow-btn.svg'; echo file_get_contents($path); ?>
</div>
<?php endwhile;
wp_reset_postdata();
else:
echo 'Sin resultados';
print_r($args);
endif;
die();
}
PHP action 2:
add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); //
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');
function filterduracionajax(){
if( $args = array(
'posts_per_page' => -1,
'hide_empty' => 1,
'post_type' => 'tours',
'meta_key' => 'dias',
'orderby' => 'meta_value',
'order' => 'ASC',
) ) :
// create $args['tax_query'] array if one of the following fields is filled
if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {
// for taxonomies / categoria
if( isset( $_POST['filtrodestino'] ) ) {
$args['tax_query'][] =
array(
'taxonomy' => 'destino',
'field' => 'slug',
'terms' => $_POST['filtrodestino']
);
}
}
// create $args['tax_query'] array if one of the following fields is filled
if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {
// for taxonomies / categoria
$args['tax_query'][] =
array(
'taxonomy' => 'categoria',
'field' => 'id',
'terms' => $_POST['categoriafilter']
);
}
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ): ?>
<div class="select-holder">
<label>Duración del viaje</label>
<select name="duracionfilter" id="resultselect">
<option disabled="" selected="" value="0"> </option>
<option value="0" >Todas las duraciones</option>
<?php $unique_dias = array();
while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $dias = get_field('dias');
if( ! in_array( $dias, $unique_dias ) ) :
$unique_dias[] = $dias; ?>
<?php endif;
endwhile;
natsort($unique_dias);
foreach ( $unique_dias as $duraciones ) :
echo '<option value="'.$duraciones.'">'.$duraciones.'</option>';
endforeach;
?>
</select></div>
<?php endif;
endif;
die();
}
Im very new with Ajax, this code is made by pieces of tutorials i found. The code is mostly made following this tutorial: https://rudrastyh.com/wordpress/ajax-post-filters.html
I just need both php actions to execute on "form" change and update the "tours" on #response div and also update the select input with #resultselect id.
Thanks!
Thanks to #lewis4you I'm able to get the data on the 2 divs at the same time. But i fail to understand how to execute both actions at the same time, but with different actions from functions.php
This
add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); //
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');
has to return data to #resultselect
and
add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');
has to return data to #response div
My main problem is that i dont know how to select the action i want to execute in
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
I didn't read the question fully but I think you want something like this:
$('#filtro').change(function() {
var filter = $('#filtro');
ajax1(filter);
ajax2(filter);
});
function ajax1(filter) {
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
// ... further code
}
function ajax2(filter) {
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
// ... further code
}
The scenario where you send the data to the same controller from one $.ajax call:
$('#filtro').change(function() {
var filter = $('#filtro');
ajax1(filter);
});
in controller you have to store the data into array with keys so you can access it later in ajax success() function
public function someFunction($dataFromAjax) {
// do something with $dataFromAjax
$dataForDivs = [
'div1' => 'some data',
'div2' => 'some data2'
];
return $dataForDivs;
}
then in your $ajax in success:function(data) you can access that data with
success:function(data) {
let div1Data = data.responseJSON.div1;
let div2Data = data.responseJSON.div2;
filter.find('button').text(div1Data); // changing the button label back
$('#response').html(div2Data); // insert data
console.log(div1Data, div2Data);
},
Have you thought of using JS's Fetch API instead of jQuery's Ajax? Fetch returns a promise then it can execute a chain of .then() blocks where you can put another fetch() to your PHP url.
See an example here:
using a fetch inside another fetch in javascript

Select2 multi-value select boxes can't load data in CI

I create a search box with select2 multi-value select boxes. the data on select2 must list of Title Name that are based on the Project I selected before. But Select2 cannot load the data. Also, there is an error
"Uncaught Error: Option 'ajax' is not allowed for Select2 when attached to a element" how to solve it?
This is Controller Page
function get_title_by_keyword()
{
$keyword = $_POST['keyword'];
$cos_id = implode(',', $_POST['cos_id']);
if (isset($keyword)&&isset($cos_id))
{
die(json_encode($this->menu_model->get_title_by_keyword($keyword,$cos_id)));
}
}
This is Model Page
function get_title_by_keyword($keyword,$cos_id){
$query="SELECT t.id as id , t.name text
FROM db_mstr.m_title t
JOIN db_mstr.m_os os ON t.os_id = os.id
JOIN db_mstr.m_os osC ON os.cos_id = osC.id
JOIN db_mstr.m_bp_title bpt ON t.id = bpt.title_id AND bpt.is_deleted=0
JOIN db_mstr.m_bp bp ON bpt.bp_id = bp.id
where t.id like '%$keyword%' and osC.id in ($cos_id)
GROUP BY t.name";
return $this->db->query($query)->result();
}
This is View Page and JS
<label class="control-label col-sm-1">Project</label>
<div class="col-sm-4">
<select required multiple="multiple" id="title_cos" name="title_cos" class="" style="width:100%" data-placeholder="">
<?php
foreach ($comboCompany as $key)
{
?><option value="'<?=$key->value?>'" > <?=$key->text?> <?php
}
?>
</select>
</div>
<label class="control-label col-sm-1" style="padding-left: 4px;padding-right: 3px;">Title Name</label>
<div class="col-sm-4">
<select required multiple="multiple" class="" id=title_list name="title_list" style="width:100%">
<?php
foreach ($comboTitle as $key)
{
?><option value="<?=$key->id?>" > <?=$key->text?> <?php
}
?>
</select>
</div>
<script>
$(document).ready(function(){
$("#title_list").select2({
ajax: {
url: '<?=base_url();?>index.php/menu/get_title_by_keyword',
dataType: 'json',
type: "POST",
quietMillis: 1000,
data: function (term) {
return {
keyword: term,
cos_id: $('#title_cos').val()
};
},
results: function (data) {
return {
results: data
};
}
},
placeholder: 'Search for Title',
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3,
});
});
</script>

Jquery UI Autocomplete in codeigniter using table oracle

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
};
}));
});
},
});

Jquery and PHP , autocomplete

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();

Categories

Resources