Cakephp 3.0 autocomplete jquery ui - javascript

I need to know why the following isnt working .This code will extract data from index controller to search get json data.Neither does any request is made and nothing happens
I'm new to both Cakephp 3.0
I'm trying to get an autocomplete / autosuggest working in CakePHP 3.0 but everything I find is either for 1.3 or not for Cake at all and I don't know what to do to get it working properly.I precisely need it for cakephp 3.0
snippet
1.CarsController.php
This is carscontroller accesses when an ajax request and will encode in json data
2.CarsTable.php
fetches data from the carstable
3.index.ctp
is the view page and autocomplete method
<?php
namespace App\Controller;
use App\Controller\AppController;
class CarsController extends AppController {
public function index() {
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax')) {
$term = $this->request->query('term');
$carNames = $this->Car->getCarNames($term);
$this->set(compact('carNames'));
$this->set('_serialize', 'carNames');
}
}
}
?>
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class Carstable extends AppModel {
public function getCarNames ($term = null) {
if(!empty($term)) {
$cars = $this->find('list', array(
'conditions' => array(
'name LIKE' => trim($term) . '%'
)
));
return $cars;
}
return false;
}
}
?>
<?php
//let's load jquery libs from google
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));
//load file for this view to work on 'autocomplete' field
//form with autocomplete class field
echo $this->Form->create();
echo $this->Form->input('name', array('class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->end();
?>
<script type="text/javascript">
(function($) {
$('#autocomplete').autocomplete({
source: "<?php (array('controller'=>'Cars','action'=>'search')); ?>",
datatype:"json",
minLength: 1
})
})
</script>

This code snippet will work for autocomplete in cakephp 3.0
View for search \Template\post\
Search.ctp
<?php
use Cake\Routing\Router;
use Cake\View\Helper\UrlHelper;
?><div class="ui-widget">
<?php
echo $this->Form->create('Posts', array('action' => 'search'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->end();
?></div><div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'<?php echo Router::url(array("controller" => "posts", "action" => "search")); ?>',
minLength: 1
}); });
</script>
In your controller add this function .Change database and other variable properly.
src\Controller\PostController.php
public function search()
{
if ($this->request->is('ajax')) {
$this->autoRender = false;
$name = $this->request->query('term');
$results = $this->Posts->find('all', array(
'conditions' => array('Posts.title LIKE ' => '%' . $name . '%')
));
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['title'] , 'value' => $result['title'] );
}
echo json_encode($resultArr);
}}
In routes.php add this line
Router::extensions('json', 'xml');

Related

Jquery Codeigniter - Autocomplete not working

I am facing a problem with autocomplete in codeigniter. When inserting some text on input, it shows a dropdown but no value in there. Looks like this: Screenshot
Viewing error on console : Screenshoot
Here is my code :
Model
var $unit_table = "sales_unit";
public function getUnit($searchTerm)
{
$this->db->like('nopol', $searchTerm, 'both');
$this->db->order_by('nopol', 'ASC');
$this->db->limit(10);
return $this->db->get($this->unit_table)->result();
}
Controller
function jsonUnitAutocomplete()
{
if (isset($_GET['term'])) {
$result = $this->m_admin->getUnit($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$data[] = array(
'nopol' => $row->nopol,
'type' => $row->type,
'kategori' => $row->kategori,
'seat' => $row->seat
);
echo json_encode($data);
}
}
}
View
<input type="text" class="form-control" name="npl" id="drop-npl"><br>
<input type="text" class="form-control" name="tyunit"><br>
<input type="text" class="form-control" name="kg"><br>
<input type="text" class="form-control" name="seat"><br>
<script>
$(document).ready(function() {
$("#drop-npl").autocomplete({
source: "<?php echo site_url('control_admin/jsonUnitAutocomplete') ?>",
select: function(event, ui) {
$('[name="npl"]').val(ui.item.nopol);
$('[name="tyunit"]').val(ui.item.type);
$('[name="kg"]').val(ui.item.kategori);
$('[name="seat"]').val(ui.item.seat);
}
});
});
</script>
Isn't you just read incorrect query param name? and in the Controller you not declare else statement for your if-else, so the result will be undefined
From what I noticed, I assumed No.Polisi is input text with the name "npl". So you can change 'term' on your controller into 'npl', like below:
function jsonUnitAutocomplete()
{
if (isset($_GET['npl'])) {
$result = $this->m_admin->getUnit($_GET['npl']);
if (count($result) > 0) {
foreach ($result as $row)
$data[] = array(
'nopol' => $row->nopol,
'type' => $row->type,
'kategori' => $row->kategori,
'seat' => $row->seat
);
echo json_encode($data);
}
}
}

Javascript - How to pull a WooCommerce variable in PHP?

I'm trying to execute some PHP code that is using the WooCommerce variable to get the order ID.
add_action('add_meta_boxes', 'gen_order_meta_boxes');
function gen_order_meta_boxes()
{
add_meta_box(
'woocommerce-order-gen',
__( 'TESTNG' ),
'order_meta_box_gen',
'shop_order',
'side',
'default'
);
}
function order_meta_box_gen()
{
echo '<button class="button save_order button-primary alert-mass">Generate</button>';
}
add_action('admin_footer', 'lolcats');
function lolcats()
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order->get_order_number; ?>');
});
});
</script>
<?php
}
I can't seem to get it to return anything besides either null or 0.
Using something like this obviously works perfectly: window.location="dhlgen.php?order=1234"; because I'm trying to pass it through the URL to a PHP function which uses it later.
This also seems to fail, but it returns 'false':
function lolcats($post_id)
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
var data = <?php echo json_encode($order->shipping_first_name); ?>;
alert(data);
});
});
</script>
<?php
}
Thank you.
Okay, I solved it.
function lolcats()
{
global $post;
$order_id = $post->ID;
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order_id; ?>');
});
});
</script>
<?php
}

Invalid value error on Range Input WP Customizer

Range input value not working in wp customizer.
This is my class for the wordpress customizer controll and bellow that is the js code.
<?php
// Range Control Wwith Selected Value Indicator
class WP_Customize_Range_Control extends WP_Customize_Control
{
public $type = 'custom_range';
public function enqueue()
{
wp_enqueue_script(
'cs-range-control',
BLOCKS_URL . '/lib/js/controls.js',
array('jquery-ui-slider'),
false,
true
);
}
public function render_content()
{
?>
<label>
<?php if ( ! empty( $this->label )) : ?>
<span class="customize-control-title"><?php echo esc_html($this->label); ?></span>
<?php endif; ?>
<div class="cs-range-value"><?php echo esc_attr($this->value()); ?></div>
<input data-input-type="range" type="range" <?php $this->input_attrs(); ?> value="<?php echo esc_attr($this->value()); ?>" <?php $this->link(); ?> />
<?php if ( ! empty( $this->description )) : ?>
<span class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
</label>
<?php
}
}
// This is the JS
(function ($) {
$(document).ready(function ($) {
$('input[data-input-type="range"]').on('change', function () {
var val = $(this).val();
$(this).prev('.cs-range-value').html(val);
$(this).val(val);
});
})
})(jQuery);
When i change the value of the slider in WP Customizer i get an error with Invalid value. Why is happening and how do i fix it ?
Maybe try this:
'sanitize_callback' => 'intval',
Fix:
Changed the enqued script to jquery only then made
settings without sanitize callback (previously used sanitize intvl like wp says)
Something like this.
$wp_customize->add_setting( 'wca_header_opacity', array(
'default' => '',
'transport' => 'postMessage',
) );
$wp_customize->add_control(
new WP_Customize_Range_Control(
$wp_customize,
'header_opacity',
array(
'label' => __('Header Opacity When Fixed'),
'section' => 'wca_header_section_design',
'settings' => 'wca_header_opacity',
'context' => 'wca_header_opacity',
'description' => __('Set transparency for header when is fixed for an awesome effect !'),
'input_attrs' => array(
'min' => 0,
'max' => 1,
'step' => 'any',
),
'priority' => 10
)
)
);

how to create an autocomplete textbox in wordpress?

Hi i am developing a plugin in wordpress.
i tried code for create autocomplete text box in my customized form.
Ajax Calling function
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
foreach($result as $dis)
{
$data.=$dis->city."<br>";
}
echo $data;
die();
}
add_action( 'wp_ajax_city_action', 'city_action_callback' );
add_action( 'wp_ajax_nopriv_city_action', 'city_action_callback' );
Shortcode function
function my_search_form() {
?>
<script>
jQuery(document).ready(function($) {
jQuery('#city').keyup(function() {
cid=jQuery(this).attr('val');
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
//alert(response);
});
});
});
</script>
<input type="text" id="city" name="city" autocomplete="off"/>
<?php
}
this code return related results perfectly in variable response.
But i don't know how create a text box look like a autocomplete box.
Please explain me how to do that in wordpress?
Just add a div under the input tag
HTML Code:
<input type="text" id="city" name="city" autocomplete="off"/>
<div id="key"></div>
replace the div after the success on you ajax.
Ajax Code:
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
$('#key').html(response);
});
PHP Code:
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
echo '<ul>'
foreach($result as $dis)
{
echo '<li>'.$dis->city.'</li>';
}
echo '</ul>'
die();
}

Creating a PHP json feed and successfully linking it to javascript

I have a project i am working on that requires sending information from database through a php script using json feed to javascript. Here are the scripts:
This is the javascript:
<link rel= 'stylesheet' type='text/css' href='fullcalendar/fullcalendar/fullcalendar.css' />
<link rel="stylesheet" media="print" href="fullcalendar/fullcalendar/fullcalendar.print.css" />
<script type="text/javascript" src="fullcalendar/lib/jquery.min.js"></script>
<script type='text/javascript' src="fullcalendar/fullcalendar/fullcalendar.js"></script>
<script type="text/javascript" src="fullcalendar/lib/jquery-ui.custom.min.js" ></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: "public_calendar.php"
})
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
?php require_once("includes/initialize.php"); ?>
<?php require_once(LIB_PATH.DS.'database.php'); ?>
<?php
//Find all the events
$events = Event::find_all();
foreach($events as $event):
$id = (int) $event->id;
$title = "{$event->event_title}";
$start = "{$event->start_date}" ." ". "{$event->start_time}";
$end = "{$event->end_date}" ." ". "{$event->end_time}";
$url = "event_detail.php";
echo json_encode( array(
'id' => $id,
'title' => "{$title}",
'start' => "{$start}",
'end' => "{$end}",
'url' => "{$url}"
));
endforeach;
?>
This is how the php script should look like:
[ {"id":111,"title":"Event1","start":"2013-10-10","url":"http:\/\/yahoo.com\/"},
{"id":222,"title":"Event2","start":"2013-10-20","end":"2013-10-22","url":"http:\/\/yahoo.com\/"}
]
This is how it looks like now:
{"id":12,"title":"Matriculation","start":"2013-11-5 08:00","end":"2013-11-5 17:00","url":"event_detail.php"}
{"id":13,"title":"Exam","start":"2013-11-30 09:00","end":"2013-11-30 16:00","url":"event_detail.php"}
{"id":2,"title":"Convocation","start":"2013-12-11 08:00","end":"2013-12-11 19:00","url":"event_detail.php"}
Thanks for your help in advance.
The best way to achieve the result you want is to create an array in PHP, then use json_encode() to create the output. You're already doing some of this - you just need a little more:
<?php
//Find all the events
$events = Event::find_all();
$eventList = array(); // Assemble list of all events here
foreach($events as $event):
$eventList[] = array( // Add our event as the next element in the event list
'id' => (int) $event->id,
'title' => $event->event_title,
'start' => $event->start_date." ".$event->start_time,
'end' => $event->end_date." ".$event->end_time,
'url' => "event_detail.php"
);
endforeach;
echo json_encode($eventList); // encode and output the whole list.
?>
I've also simplified and shortened some of your code to remove the unnecessary double quotes.

Categories