Autocomplete implementation in cakephp 2.4 - javascript

Hello Guys i am very new to cakephp and i want to implement autocomplete in my project. I have downloaded two javascript file jquery.autocomplete.js and jquery.autocomplete.min.js and placed them both in my webroot directory. i have a field named city in my database which i have to autocomplete. the problem is my sutocomple is not firing or even not showing alert when key is pressed.
my javascript code is
<script src="../../webroot/js/jquery.autocomplete.js"
type="text/javascript"></script>
<script src="../../webroot/js/jquery.autocomplete.min.js"
type="text/javascript"></script>
$(function() {
$('#Usercity').autocomplete({
alert("ashish");
//dataType: "json"
minLength: 1,
source: function( request, response ) {
$.ajax({
url: "/User/autoComplete",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
term: request.term
},
success: function( data ) {
response( $.map( data, function( el ) {
return { label: el.id, value: el.city }
}));
}
});
}
});
});
</script>
echo $this->Form-
>input('city',array('type'=>'text','label'=>'City'));
Controller code
public function autoComplete() {
Configure::write('debug', 0);
$this->layout = 'ajax';
$query = $_GET['term'];
$items = $this->User->find('all', array(
'conditions' => array('User.city LIKE' => $query . '%'),
'fields' => array('city')));
foreach ($items as $item) {
$data[] = $item['Item'];
}
$data = json_encode($data);
echo $data;
exit;
}
}

To fix problem
the problem is my sutocomple is not firing or even not showing alert
when key is pressed.
you need to load jQuery lib before autocomplete.js something like
<script src="../js/jquery-last.version.number.js"></script>
or if you want cakephp to do it for you (no need to write '.js')
echo $this->Html->script(array(
'jquery-1.10.2.min',
'jquery.autocomplete'
));

Related

Can't Output Anything from WordPress AJAX, no Errors

I have an issue with Ajax in WordPress, I viewed 1000 posts about AJAX for a WordPress, but nothing. Everything seems ok.
I have a button with data-id attribute for every post on my index page, inside data-id I have its post id.
So idea is simple when someone click on this button I want to create a div with text, which will be post id. But I get nothing, I haven't any error, in my console everything is ok, but div is not created.
My enqueue scripts:
function _themename_assets() {
wp_enqueue_script( '_themename-dummy-scripts', get_template_directory_uri() . '/dist/assets/js/ajax.js', array('jquery'), '1.0.0', true );
wp_localize_script('_themename-dummy-scripts', 'viasun_dummy_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
add_action('wp_enqueue_scripts', '_themename_assets');
My JS:
$('.c-post__button a').on( 'click', function(e){
e.preventDefault();
var button = $(this);
var id = button.data('id');
var data = {
id: id,
action: "viasun_dummy_ajax_data_action"
};
$.ajax({
url: viasun_dummy_ajax.ajax_url,
data: data,
type: "POST",
beforeSend: function( ) {
console.log("sending");
},
success: function(message) {
if( data ) {
$("body").append(data);
console.log(data);
}
},
error: function() {
console.log("error");
}
} );
});
My action for ajax:
function viasun_dummy_ajax_data_action(){
$id = $_POST['id'];
echo '<div class="id-container">' . $id . '</div>';
wp_die();
}
add_action( 'wp_ajax_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
add_action( 'wp_ajax_nopriv_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
In my console from js I get:
Object { id: 15, action: "viasun_dummy_ajax_data_action" }
And XHR in console says 200 OK.
What am I doing wrong? Can you help me, please?

Pass JavaScript variable to PHP function within Ajax call?

I'm trying to create an ajax search form that gets WordPress posts if the search term is found within the post title. This is my PHP function:
function get_records_ajax($query) {
$args = array(
'post_type' => array('record'),
'post_status' => array('publish'),
'posts_per_page' => 999,
'nopaging' => true,
'meta_query' => array(
'key' => 'title',
'value' => $query,
'compare' => 'IN',
)
);
$ajaxposts = get_posts( $args );
echo json_encode( $ajaxposts );
exit;
}
And this is my jQuery function:
jQuery('.rrm_search_form').on('submit', function(e){
e.preventDefault();
let query = jQuery(this).find('.rrm_search_input').val();
console.log('search submitted for ' + query);
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "json",
data: { action : `get_records_ajax(${query})` },
success: function( response ) {
jQuery.each( response, function( key, value ) {
console.log( key, value );
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
}
});
});
I've tried lots of different syntax to try and pass the variable within the data action of my ajax call but nothing's working. Any ideas how I might be able to do this?
I assume your ajax URL is fine and loading in the website.
Now all you have to modify your JS scripts and need to add hooks in PHP section. First in your JS script modify the data: line as follows:
data: { action : 'get_records_ajax', query: query },
Also You can add security check if you want. but leave it now.
Secondly, in your PHP file add the following code..
add_action( "wp_ajax_nopriv_get_records_ajax", 'get_records_ajax' );
add_action( "wp_ajax_get_records_ajax", 'get_records_ajax' );
and then in your get_records_ajax receive the query value
function get_records_ajax(){
$query = sanitize_text_field($_POST['query']);
//then your rest code
}
It will return all the post. Now you need to adjust your JS code in the success block :
success: function( response ) {
console.log(response)
//adjust here with your HTML dom elements
}

Wordpress ajax function parameter not working

I am using wordpress ajax and following code not passing parameter value metakey: id to $_POST["metakey"]. So var_dump($_POST) shows array(0) { }
if I enter static value of variable in PHP function $key=<any meta key> then its works fine
jQuery(".selectbox").change(function(){
var id = this.id;
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get-mata-value",
metakey: id
}),
success: function( response ) {
jQuery.each(response ,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
});
});
PHP:
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$result=
$wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$key
) );
return($result);
exit();
}
Did you try this?
data: (JSON.stringify({
action: "get-mata-value",
metakey: id
})),

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

Variations Javascript not working when single_product_content is loaded via Ajax (WooCommerce)

In my WooCommerce Shop Templates I am loading the single-product-content dynamically in the archive-product.php page with Ajax. This part is working.
But the javascript to choose the product variations is missing so I tried to add the script to the html after the successful ajax request.
I could load the script but I still can not choose a product variation. No events are triggered. Seems like I am missing something...
My Javascript:
jQuery('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript () {
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
jQuery.getScript("../wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
In functions.php
add_action( 'wp_enqueue_scripts', 'child_add_scripts' );
function child_add_scripts(){
wp_register_script( 'pa_script', get_stylesheet_directory_uri() . '/main.js', array('jquery'), true );
wp_localize_script( 'pa_script', 'singleprojectajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('pa_script');
}
function load_single_product_content () {
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
echo "There were no products found";
}
}
wp_die();
}
add_action('wp_ajax_load_single_product_content', 'load_single_product_content');
add_action('wp_ajax_nopriv_load_single_product_content', 'load_single_product_content');
The WooCommerce script "add-to-cart-variations.js":
https://searchcode.com/codesearch/view/95139130/
Did you try like:
jQuery(document).ready(function($) {
"use strict";
$('.project-preview').on('click',function(){
var theId = $(this).attr('data-project-id');
var div = $('#product-container');
$.ajax({
type: "POST",
url: singleprojectajax.ajaxurl,
data : {action : 'load_single_product_content', post_id: theId },
success: function(data){
div.html(data);
},
complete: function(){
loadVariationScript();
},
error : function() {
}
});
});
function loadVariationScript() {
$.getScript("www.yoursitenamehere.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.min.js");
$.getScript("www.yoursitenamehere.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js");
}
});
You used $ for your AJAX, so it's safe to assume you're already inside the document ready environment. So you don't need to use jQuery.
I placed the $.getScript() in the complete ajax method. Plus you need to include the entire url to your page.

Categories

Resources