I have problem with autocomplete in Codeigninter and Jquery
I have a controller
<?php
public function search() {
$user = $_GET['term'];
$query = $this
->db
->select('nama_kota')
->like('nama_kota', $user)
->get('kota');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row_set[] = htmlentities(stripslashes($row['nama_kota']));
}
echo json_encode($row_set);
}
}
?>
I have a view
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
$("#user-input").autocomplete({
source: availableTags
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
everything its okay
but I'm trying multiple values
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#user-input").autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
no work and availableTags only read addres url no function in controller
whats wrong guys please help me, Thanks
which type off output you need If you need like this
eg.
name,
address,
blood_group.
with output of Autocomplete call
Sorry For late reply I am very very busy in my work
this is JS call to Controller
<script>
jQuery("#h_student_name").autocomplete({
minLength: 0,
source: "DropdownController/hostel_students/" + $("#h_student_name").val(),
autoFocus: true,
scroll: true,
dataType: 'jsonp',
select: function (event, ui) {
jQuery("#h_student_name").val(ui.item.contactPerson);
jQuery("#h_student_id").val(ui.item.code);
}
}).focus(function () {
jQuery(this).autocomplete("search", "");
});
</script>
and this is controller for call
<?php
//Hostel Student Auto compelete
public function hostel_students(){
$term = trim(strip_tags($this->input->get('term')));
if( $term == ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1));
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
} else if($term != ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1), $like);
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
}
}
?>
and this is model for call
<?php
// Hostel student autocomplete
public function hostel_students($where, $like = NULL){
if($like):
$this->db->like('student_name', $like);
$this->db->or_like('form_no', $like);
$this->db->or_like('college_no', $like);
endif;
$this->db->join('student_record', 'student_record.student_id=hostel_student_record.student_id');
return $this->db->where($where)->get('hostel_student_record')->result();
}
}
?>
have any issue comment me I will online today
Related
In cart.php I have an input where user can input your own price
<input type="number" id="customPrice">
<div data-id="<?php echo $product_id ?>" id="updateCart">Update</div>
And I have a js function for make ajax request with product id and new price data
<script type="text/javascript">
jQuery(function ($) {
let customPrice = document.getElementById('customPrice');
let price = customPrice.value;
let updateCart = document.getElementById('updateCart');
let id = updateCart.dataset.id
updateCart.addEventListener('click', function () {
$.ajax({
url: "../wp-admin/admin-ajax.php",
data: {action: "add_custom_price", id: id, price: 10},
type: "POST",
success(data) {
if (data) {
console.log(data)
}
$("[name='update_cart']").trigger("click");
}
});
});
});
</script>
In my functions.php i have
function add_custom_price($cart)
{
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (isset($_POST['price']) && $_POST['id']) {
$price = intval($_POST['price']);
// $id = intval($_POST['id']);
foreach ($cart->get_cart() as $cart_item) {
$cart_item['data']->set_price($price);
}
}
}
add_action('wp_ajax_add_custom_price', 'add_custom_price');
add_action('wp_ajax_nopriv_add_custom_price', 'add_custom_price');
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
But it don't work. I have 500 error
Where is my mistake? Or how i can do it or another way? Any suggestion please
You need to get the product, then affect the price, then save
function add_custom_price($cart) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (isset($_POST['price']) && $_POST['id']) {
$price = intval($_POST['price']);
$id = intval($_POST['id']);
// Get product
$product = wc_get_product($id);
$product->set_regular_price($price);
$product->save();
// delete the relevant product transient
wc_delete_product_transients( $id );
}
}
So, I have this jquery code in my php page that gets data from a mysql table:
$(function() {
$("#tracking_num").autocomplete({
source: "func/populate.php",
minLength: 2,
select: function(event, ui) {
$('#name').val(ui.item.name);
$('#particulars').val(ui.item.particulars);
$('#remarks').val(ui.item.remarks);
$('#location').val(ui.item.location);
}
});
});
I'm challenged to get the data immediately into the fields without selecting it from the drop down box. Do you guys have any idea how to do it? Here's my the func/populate.php file:
$return_arr = array();
$fetch = mysql_query("SELECT * FROM tbl_document WHERE tracking_number = '" . mysql_real_escape_string($_GET['term']) . "' ORDER BY id DESC LIMIT 1");
while ($row = mysql_fetch_array($fetch) ) {
$row_array['name'] = $row['name'];
$row_array['particulars'] = $row['particulars'];
$row_array['remarks'] = $row['remarks'];
$row_array['location'] = $row['location'];
$row_array['value'] = $row['tracking_number'];
array_push($return_arr,$row_array);
}
mysql_close();
echo json_encode($return_arr);
Have you tried :
$(function() {
$("#tracking_num").autocomplete({
source: "func/populate.php",
minLength: 2,
create: function(event, ui) {
$('#name').val(ui.item.name);
$('#particulars').val(ui.item.particulars);
$('#remarks').val(ui.item.remarks);
$('#location').val(ui.item.location);
}
});
});
?
I have a jquery script that works with a city search field
Script
<script type="text/javascript">
$(document).ready(function()
{
var ac_config =
{
source: "demo_cities.php",
select: function(event, ui)
{
$("#City").val(ui.item.City);
$("#Country").val(ui.item.Country);
$("#DestinationId").val(ui.item.DestinationId);
},
minLength:3
};
$("#City" ).autocomplete(ac_config);
});
</script>
and php code is
<?php
$cities= array(
array('City'=>'Barcelona',
Country=>'SP',
DestinationId=>'10001'),
....... );
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $City)
{
if(stripos($City['City'], $term) !== false)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
How can i make the script to search only by the first 3 charachers from the City name
In your PHP code, you're looking for a city that contains a string in city name. If you want to show cities that starts with specific chars, you could use substr
<?php
$cities= array(
array('City'=>'Barcelona',
'Country'=>'SP',
'DestinationId'=>'10001'
),
//more cities ...
);
$term = strtolower(trim(strip_tags($_GET['term'])));
$matches = array();
foreach($cities as $City)
{
if(strtolower(substr($city['city'], 0, strlen($term))) == $term)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
normally city will not change its name, so I put city name in a js file, then let FE to do search,
and autocomplete part seems no question.
I have a question about wordpress, I just added a button called Add Slider in Add/Edit Post Page.
here's my code in my function.php :
//Add button to create slider
add_action('media_buttons','add_my_media_button',15);
function add_my_media_button(){
echo 'Add Slider';
}
function include_media_button_js_file(){
wp_enqueue_script('media_button',get_bloginfo('template_directory').'/js/media_button.js',array('jquery'),'1.0',true);
}
add_action('wp_enqueue_media','include_media_button_js_file');
and this my media_button.js code
jQuery(function($){
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
})
function open_media_window(){
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
var self = this; //needed to retrieve the function below
this.window.on('select',function(){
var files = self.window.state().get('selection').toArray();
var values;
for (var i = 0; i < files.length; i++) {
var file = files[i].toJSON();
if(values===undefined){
var values = file.url;
}
else{
var values = values+','+file.url;
}
};
wp.media.editor.insert(values);
});
}
this.window.open();
return false;
}
});
after user select the pictures in media window and press Insert button it will add url value of pictures to content editor post box.
My question is how to add this value automatically on custom fields box and add/update that automatically without click add custom field button.
So user can add / update custom fields for that pictures url without view/ check custom fields to view in post editor on Screen Options in wordpress.
Please help me for this question, Thanks.
I modify my jquery / js like this..
$(document).ready(function(){
// $('#insert-my-media').click(open_media_window);
if($('#images_id').val() != '' && $('#images_url').val() != ''){
$('#open_media').text("Edit Slider");
}
$('#open_media').click(function(e){
e.preventDefault();
var target = $('#images_id');
var target_url = $('#images_url');
var btnSave = $('#publishing-action input.button');
if(target.val() == '' && target_url.val() == ''){
var wpmedia = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
wpmedia.on('select', function(){
var ids = [];
var urls = [];
var models = wpmedia.state().get('selection').toArray();
for (var i = 0; i < models.length; i++) {
var file = models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Adding...");
btnSave.click();
});
wpmedia.open();
}else{
wp.media.gallery
.edit('[gallery ids="'+ target.val() +'" urls="'+ target_url.val() +'"]')
.on('update', function(g){
var ids = [];
var urls = [];
for (var i = 0; i < g.models.length; i++) {
var file = g.models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Editing...");
btnSave.click();
});
}
});
$('#save_desc').click(function(e){
e.preventDefault();
var target = $('#desc_editor');
var btnSave = $('#publishing-action input.button');
target.val(target.val());
btnSave.click();
});
$('#delete_slider').click(function(e){
e.preventDefault();
/*var target = $('#images_id');
var target_url = $('#images_url');*/
var btnSave = $('#publishing-action input.button');
/*target.val("");
target_url.val("");*/
$('#deleting_slider').val("Deleting...");
$('#delete_slider').text("Deleting...");
btnSave.click();
});
});
and then I make file called metabox.php to create metabox
<?php
function koplan_add_metabox(){
add_meta_box(
'koplan_metabox_gallery',
'Slider Gallery',
'koplan_show_metabox',
'post'
);
}
function koplan_add_maps_metabox(){
add_meta_box(
'koplan_metabox_maps',
'Maps Descriptions',
'koplan_show_maps_metabox',
'post'
);
}
function koplan_show_metabox($post){
$ids = get_post_meta($post->ID, 'gallery_images', true);
$urls = get_post_meta($post->ID,'images',true);
?>
Add Slider
<hr>
<input type="hidden" name="gallery_images" id="images_id" value="<?php echo $ids; ?>">
<input type="hidden" name="gallery_urls" id="images_url" value="<?php echo $urls; ?>">
<input type="hidden" name="deleting_slider_post_meta" id="deleting_slider" value="<?php echo $urls; ?>">
<?php
if($ids=="" and $urls==""){
return;
}
else{
echo do_shortcode('[gallery ids="'.$ids.'" urls="'.$urls.'"]');
}
?>
<hr>
Delete Slider
<?php
}
function koplan_save_gallery_metabox($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if(! isset($_POST['gallery_images']) && !isset($_POST['gallery_urls'])){
return;
}
$ids = sanitize_text_field( $_POST['gallery_images'] );
$urls = sanitize_text_field( $_POST['gallery_urls'] );
$terms = wp_get_object_terms( $post_id, 'category', array( 'fields' => 'names' ) );
/*$termsname = $terms[0]->name;*/
if(strlen($terms[1]) > strlen($terms[0])){
$term = $terms[1];
}
else{
$term = $terms[0];
}
$sldata = '<slider images="'.$term.'" />';
update_post_meta($post_id, 'slider', $sldata);
update_post_meta($post_id, 'gallery_images', $ids);
update_post_meta($post_id, 'images', $urls);
if(isset($_POST['deleting_slider_post_meta']) && $_POST['deleting_slider_post_meta'] != ""){
delete_post_meta($post_id, 'slider', $sldata);
delete_post_meta($post_id, 'gallery_images', $ids);
delete_post_meta($post_id, 'images', $urls);
}
}
function koplan_show_maps_metabox($post){
$desc = get_post_meta($post->ID,'mapsdesc',true);
if($desc!=""){
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"><?php echo $desc; ?></textarea>
<?php
}else{
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"></textarea>
<?php
}
?>
<hr>
Save
<?php
}
function koplan_save_maps_desc_metabox($post_id){
if (define('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if(!isset($_POST['maps_descriptions'])){
return;
}
$desc = $_POST['maps_descriptions'];
update_post_meta($post_id,'mapsdesc',$desc);
}
add_action( 'add_meta_boxes', 'koplan_add_metabox' );
add_action('add_meta_boxes','koplan_add_maps_metabox');
add_action( 'save_post', 'koplan_save_gallery_metabox' );
add_action( 'save_post', 'koplan_save_maps_desc_metabox' );
?>
I said problem solved, case closed. Thanks all, thanks stackoverflow
I dont know if i am tired or why i cannot get it right please help what i need is
<script language="javascript">
$(document).ready(function(){
getResultsCountry();
})
function getResultsCountry() {
$.ajax({
url:'suggest_country.html',
type:'POST',
data: 'q=',
dataType: 'json',
success: function( json ) {
$('#country')[0].options.length = 0;
$.each(json, function(i, value) {
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value).attr('value', value).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value).attr('value', value));
};
});
}
});
};
</script>
Code in external file looks like
<?php
$results = mysql_query('SELECT DISTINCT country FROM MyTable WHERE country LIKE \'%\' ORDER BY country');
while( $result = mysql_fetch_array($results) ) {
$cities = $cities.' short = \''.$result['country'].'\' OR';
}
$cities = substr($cities, 1,strlen($cities)-3);
$results2 = mysql_query('SELECT full, short FROM `Countries` WHERE '.$cities);
$json = array();
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = $result2['short'].','.$result2['full'];
}
echo json_encode( $json );
mysql_close($db2);
?>
Response i am getting is
["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA","KY,CAYMAN ISLANDS","CN,CHINA"]
What i need is to fill it in the options for tag i got this part too, but i cannot make it fill country code AG as value and name as name like
<option value="AG">Antigua</option>
please break it down for me i am really confused and tired its been hours of headache.
You need to split values
$.each(json, function(i, value) {
var arr_values = value.split(',');
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0]).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0])));
};
});
It would make your ajax callback much easier if you didn't have to split your strings..
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = array('short'=>$result2['short'],
'full' => $result2['full']
);
}
And then you can parse by
$.each(json, function(i, value) {
if (value['full']=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value['full']).attr('value', value['short']).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value['short']).attr('value', value['full'])));
};
});