Jquery UI Autocomplete in codeigniter using table oracle - javascript

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

Related

how to pass data coming from laravel query as a json object to the function in javascript

i am actually using graphs in my project for which i am passing dynamic data from controller to blade and then in the js script. The js function in the blade accept the array of objects and i dont know how to assign the data from the controller to that js function.
$data['typesBasedProperties'] = DB::table('properties')
->join('property_types', 'properties.property_type', 'property_types.id')
->select('property_types.types as label', DB::Raw('COUNT(properties.id) as value'))
->whereIn('properties.id', $property_ids)
->groupBy('label')
->get()
->toJson();
and this is the js function
var donutChart = function(){
Morris.Donut({
element: 'morris_donught',
data: [
{
label: " Download Sales ",
value: 12,
}, {
label: " In-Store Sales ",
value: 30
}, {
label: " Mail-Order Sales ",
value: 20
}
],
resize: true,
redraw: true,
colors: ['#2b98d6', 'rgb(59, 76, 184)', '#37d159'],
//responsive:true,
});
}
I think you need to do something like this:
<script>
var typesBasedProperties = {!! $typesBasedProperties !!}
</script>
After this you have typesBasedProperties object available in all your js code.
Check out laravel documentation for more info.
You can use ajax request to fetch data from laravel controller to javascript or JQuery.
here's some example
controller
function bbq(Request $r){
$data = DB::select('CALL bukubesar('.$r->no.')');
$node = DB::select('CALL infonode('.$r->no.')');
return array(
'data' => $data,
'node' => $node
);
}
route (I'm using Group)
Route::controller(CPembukuan::class)->group(function () {
Route::get ('/pembukuan-besar', 'bukubesar');
Route::get ('/pembukuan-besar/query', 'bbq' );
Route::get ('/pembukuan-labarugi', 'labarugi' );
Route::get ('/pembukuan-labarugi/query', 'lrq' );
});
ajax (JQuery) on html or blade file
//a variable to pass to controller (optional)
val = $('#kode').val();
$.ajax({
type: "get",
url: "/pembukuan-besar/query",
data: {
'no': val // the data represented as 'no'
},
success: function(data) {
console.log(data); // to view the data in console
//do anything you want here
}
});

WooCommerce Ajax add to cart with additional custom data

I am having some difficulties with trying to add to cart with custom data from the front end.
My current PHP from the backend is as follows - this is placed in my functions.php for my child-theme (This code is from the following post: Adding a product to cart with custom info and price - considering I am indeed a PHP-noobie):
<?php // This captures additional posted information (all sent in one array)
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {
global $woocommerce;
$new_value = array();
$new_value['_custom_options'] = $_POST['custom_options'];
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
// This captures the information from the previous function and attaches it to the item.
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key) {
if (array_key_exists( '_custom_options', $values ) ) {
$item['_custom_options'] = $values['_custom_options'];
}
return $item;
}
// This displays extra information on basket & checkout from within the added info that was attached to the item.
add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
function add_usr_custom_session($product_name, $values, $cart_item_key ) {
$return_string = $product_name . "<br />" . $values['_custom_options']['description'];// . "<br />" . print_r($values['_custom_options']);
return $return_string;
}
//This adds the information as meta data so that it can be seen as part of the order (to hide any meta data from the customer just start it with an underscore)
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values) {
global $woocommerce,$wpdb;
wc_add_order_item_meta($item_id,'item_details',$values['_custom_options']['description']);
wc_add_order_item_meta($item_id,'customer_image',$values['_custom_options']['another_example_field']);
wc_add_order_item_meta($item_id,'_hidden_field',$values['_custom_options']['hidden_info']);
}
and then I have a button on the frontend that runs the following script when pressed - this runs on a custom wordpress post where I have scripted have done some scripting in the background that collects information based on the users actions on the post:
function cartData() {
var metaData = {
description: 'My test Description'
another_example_field: 'test'
};
var activeVariationId = 10335;
var data = {
action: 'wdm_add_item_data',
product_id: 10324,
"add-to-cart": 10324,
quantity: 1,
variation_id: activeVariationId,
cart_item_data: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add-to-cart' ),
data: data,
beforeSend: function (response) {
//$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
//$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
alert('ajax response recieved');
jQuery( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash ] );
}
},
});
}
Unfortunately this only seems to add my current variation of the product to the to cart without any more custom information. Any help with nesting in this issue would be highly appreciated. If you need any more information and/or code examples I'd be happy to supply it :)
I think that I might have solved it, or at least parts of it with this PHP (this is really just a small modification of this code - adding $cart_item_data https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/):
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
// This is where you extra meta-data goes in
$cart_item_data = $_POST['meta'];
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
// Remember to add $cart_item_data to WC->cart->add_to_cart
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $cart_item_data) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Where this is part of the JS-function:
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: 10324,
quantity: 1,
variation_id: activeVariationId,
meta: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data, ...........
I am going to have to test it some more, as it seems now that all the data-fields also gets posted in the cart, email etc - I probably have to rewrite something so that some parts of it is hidden for the "non-admin", but available for me later on + adding custom product thumbnail on add to cart.

Laravel 'Illegal string offset 'leave_form' issue with array

I have an edit page where I display the data from a leave application form. I get an error 'Illegal string offset 'leave_form' when I update my form. I am using Vue.js and PHP. I manage to get the other data saved, that is in the leaveData object. When I try to save in the dateFrom in array of objects. leaveData['leave_form'] then I get the error. I suspect the problem lies in my foreach statement under the controller.
My array (just an example that I copied and pasted from console so you can see the object keys and values):
leaveData = [
alternativeName: "testos",
applicantSignature:"1",
applicantSignedDate:"2017-12-12",
contactDetailDuringLeave:"999999",
created_at:"2017-12-12 08:05:44",
created_by:6,
id:21,
leave_form = [
conditionsOfPay:"test",
created_at:"2017-12-12 08:05:44",
dateFrom:"2017-12-12",
dateTo:"2017-12-15",
id:15,
leave_application_id:21,
name:"Vacation Leave",
numberOfDays:2,
]
]
Here is a part of my blade HTML(just the leave_form part):
<tbody>
<tr v-for="leave in leaveData.leave_form">
<th scope="row">#{{ leave.name }}</th>
<td><input v-pikaday="leave.dateFrom" class="form-control" v-model="leave.dateFrom" type="text"/></td>
<td><input v-pikaday="leave.dateTo" class="form-control" v-model="leave.dateTo" type="text"/></td>
<td><input class="form-control" type="text" name="numberOfDays" v-model="leave.numberOfDays"></td>
<td><input class="form-control" type="text" name="conditionsOfPay" v-model="leave.conditionsOfPay"></td>
</tr>
</tbody>
Here is my Vue.js:
var leaveApply = new Vue({
el: '#leaveCreate',
data: {
leaveData: <?php echo $leaveApplication ?>,
getUserData: <?php echo $users ?>,
},
methods: {
submitForm: function(){
var that = this;
var value = that.leaveData;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $("#_token").attr("content")
}
});
$.ajax({
url: '/admin/internal/leave/update/' + value.id,
type: 'POST',
data: {
leaveData: that.leaveData,
personnelNumber: that.leaveData.personnelNumber,
user_id: that.leaveData.user_id,
alternativeName: that.leaveData.alternativeName,
contactDetailDuringLeave: that.leaveData.contactDetailDuringLeave,
applicantSignature: that.leaveData.applicantSignature,
applicantSignedDate: that.leaveData.applicantSignedDate,
managerApproval: that.leaveData.managerApproval,
managerSignedDate: that.leaveData.managerSignedDate,
},
success: function(response) {
toastr.success('Leave Application Updated');
},
error: function(error){
toastr.error('Something went wrong');
}
});
},
},
});
My Controller:
public function update (Request $request, $id){
$leaveApplication = LeaveApplication::with('user','leaveDept','leaveForm', 'leaveTask')->find($id);
$leaveApplication->personnelNumber = $request->input('personnelNumber');
$leaveApplication->alternativeName = $request->input('alternativeName');
$leaveApplication->contactDetailDuringLeave = $request->input('contactDetailDuringLeave');
$leaveApplication->managerApproval = filter_var($request->input('managerApproval'), FILTER_VALIDATE_BOOLEAN);
$leaveApplication->applicantSignature = filter_var($request->input('applicantSignature'), FILTER_VALIDATE_BOOLEAN);
$leaveApplication->applicantSignedDate = $request->input('applicantSignedDate');
$leaveApplication->managerSignedDate = $request->input('managerSignedDate');
foreach($request->input('leaveData') as $leaveData){
$leaveApplication->dateFrom = $leaveData['leave_form']['dateFrom'];
$leaveApplication->update();
}
$leaveApplication->update();
return response()->json($leaveApplication);
}
$leaveApplication = LeaveApplication::with('user','leaveDept','leaveForm', 'leaveTask')->find($id);
$leaveApplication->dateFrom = $leaveData['leave_form']['dateFrom'];
You have leave_form and LeaveForm. Maybe the problem is here. Also this code
foreach($request->input('leaveData') as $leaveData){
$leaveApplication->dateFrom = $leaveData['leave_form']['dateFrom'];
$leaveApplication->update();
}
repeats the process and saves the last foreach value into your record.
It also means that you are calling update 2 times.

Using Laravel Mentions (at.JS and Laravel) to return A username and their ID

I'm currently building a comment system and would like to include the ability to mention users and tag them, subsequently I would like the tag to have a link to their profile (In this example, it's just /profile/{id})
I am currently using Laravel Mentions to generate the auto filled list from my Users Model. I'm doing it like:
function enableMentions(elem, type, column) {
$(elem).atwho({
at: "#",
limit: 5,
displayTpl: '<li><span>${name}</span></li>',
insertTpl: '${name}',
callbacks: {
remoteFilter: function(query, callback) {
if (query.length <= 1) return;
$.getJSON("/api/mentions/" + type, {
q: query,
c: column
}, function(data) {
callback(data);
});
}
}
});
}
// My api/mentions route: Route::get('/api/mentions/{type}', 'ApiController#index');
//My api controller:
public function index($type, Request $request)
{
try {
$resultColumns = [];
$query = $request->get('q');
$column = $request->get('c');
$model = app()->make(config('mentions.' . $type));
$records = $model->where($column, 'LIKE', "%$query%")
->get();
foreach ($records as $record) {
$resultColumns[] = $record->$column;
}
return response()->json($resultColumns);
} catch (\ReflectionException $e) {
return response()->json('Not Found', 404);
}
}
And finally, initializing the at.js
<script type="text/javascript">
$(function(){
enableMentions("#mention-commentContent", "users", "Username");
});
</script>
<div contentEditable="true" id="mention-commentContent" class="user-form" name="commentContent" type="text"></div>
I'm confused on how I can modify the above to return the username and the ID assigned to them, that way I can change the ${name} to ${id} and have it link through to their profile, right?
This package may help Laravel Mentions or this .
The basic idea is getting the usernames from the database via JSON , here is how they are using it in laracasts:
$("textarea#body").atwho({
at: "#", limit: 5, callbacks: {
remoteFilter: function (t, e) {
t.length <= 2 || $.getJSON("/api/users", {q: t}, function (t) {
e(t)
})
}
}
})

Autocompleting a form in PHP/Javascript

I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.

Categories

Resources