Autocomplete dropdown in codeigniter doesn't works - codeigniter

I'm still new using jquery in codeigniter so i hope you can gladly help me.
I want to create autocomplete dropdown where when one option of autocomplete is selected, it will show other related fields.
The output become like this, there's no value to display
And this is my codes :
Model
function search_mtk($kode_mtk){
$this->db->like('kode_mtk', $kode_mtk , 'both');
$this->db->order_by('kode_mtk', 'ASC');
$this->db->limit(5);
return $this->db->get('m_mata_kuliah')->result();
}
Controller
public function get_mtk(){
if (isset($_GET['term'])) {
$result = $this->kit_model->search_mtk($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$arr_result[] = array(
'kode' => $row->kode_mtk,
'nama' => $row->nama_mtk,
);
echo json_encode($arr_result);
}
}
}
<script type="text/javascript">
$( "#kode_mtk" ).autocomplete({
source: "<?php echo base_url('fak/kit/get_mtk/?');?>",
select: function (event, ui) {
$('[name="kode_mtk"]').val(ui.item.kode);
$('[name="nama_mtk"]').val(ui.item.nama);
}
});
});
</script>
<?php echo form_open_multipart('fak/kit/file_data');?>
<div class="form-group">
<label for="program">Kode Matakuliah <span style="color:#FF0000">*</span>:</label>
<input type="text" class="form-control" id="kode_mtk" name="kode_mtk" placeholder="Type course code" />
</div>
<div class="form-group">
<label for="program">Nama Matakuliah<span style="color:#FF0000">*</span>:</label>
<input type="text" class="form-control" name="nama_mtk" placeholder="Type course name" />
</div>
<button type="submit" class="btn btn-success">Submit</button>
I hope anyone can help me with this.

Your code seems working fine but the label value not showing in the drop-down. just add value and label key value in the array to check its working or not.
Your code should be like below
$arr_result[] = array(
'kode' => $row->kode_mtk,
'nama' => $row->nama_mtk,
'value' => $row->nama_mtk,
'label' => $row->nama_mtk,
);
also, add the following call back function inside autocomplete jquery function
$( "#kode_mtk" ).autocomplete({
source: "<?php echo base_url('fak/kit/get_mtk/?');?>",
select: function (event, ui) {
$('[name="kode_mtk"]').val(ui.item.kode);
$('[name="nama_mtk"]').val(ui.item.nama);
},
response: function(event, ui){
if(ui.content.length === 0){
console.log('No results loaded!');
}else{
console.log('success!');
}
},
});
});

Related

Laravel only gets checked items from checklist

I have form with multiple input data and checklists but in controller I'm just getting checked items and no result for unchecked items.
This is what I get
"send_mail" => array:2 [▼
0 => "on"
1 => "on"
]
This is what I need
"send_mail" => array:2 [▼
0 => "off"
1 => "on"
2 => "off"
3 => "on"
]
Blade
<form enctype="multipart/form-data" action="{{route(''xxxxxxxx)}}" method="POST">
#csrf
#method('POST')
<input name="name" id="name" class="form-control">
<div class="form-check">
<input class="form-check-input" checked type="checkbox" name="send_mail[]">
<label class="form-check-label">Send Mail</label>
</div>
<div id="newRows">
// new rows (same as above) will add here by javascript
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
Controller
public function test(Request $request) {
dd($request->all());
}
By default <input type="checkbox"> won't return if it hasn't been checked.
A classic method of fixing this is to duplicate the checkbox with a hidden input:
<input type="hidden" name="send_mail" value="0" />
<input type="checkbox" name="send_mail" value="1" />
This would require, however, moving away from the array of checkboxes you currently have.
The alternative is to use Javascript to submit your form.
I faced a similar scenario back then. I managed to solve it by using JavaScript (jQuery to be specific) to submit the form.
I wrote up a reusable function to append the unchecked items.
Reusable function:
const prepareJQCheckboxFormData = (jQForm, jQSerializedFormData, checkboxNameAttr) => {
let name;
let data = [];
checkboxNameAttr?.substr(-2) === "[]"
? name = checkboxNameAttr
: name = `${checkboxNameAttr}[]`;
let hasItem = false;
jQForm.find("input[name='" + name + "']")
.add(jQForm.find("input[name='" + name?.substr(0, name.length - 2) + "']"))
.each(function () {
if (($(this).attr("checked") === true) || $(this).is(":checked")) {
hasItem = true;
}
});
if (!hasItem) {
jQSerializedFormData.push({
name, value: [""]
});
}
$(jQSerializedFormData).each(function (i, field) {
if (field.name !== name?.substr(0, name.length - 2)) {
data.push(field);
} else {
data.push({
name: `${field.name}[]`,
value: field.value
});
}
});
return data;
};
Form submission:
Assuming that the form 'id' is 'mail-form'
const form = $("#mail-form");
const btnSave = $("#mail-form button[type='submit']");
btnSave.click(function (e) {
e.preventDefault();
$.ajax({
type: form.attr("method"),
url: form.attr("action"),
processData: false, // Important for multipart-formdata submissions!
contentType: false, // Important for multipart-formdata submissions!
cache: false,
data: prepareJQCheckboxFormData(form, form.serializeArray(), "send_mail[]"),
success: function (response) {
// ...
},
error: function (jqXHR) {
// ...
},
beforeSend: function () {
// ...
}
});
});
<div class="form-check">
<input type="checkbox" name="send_mail[]">
<label>Name1</label>
</div>
<div class="form-check">
<input checked type="checkbox" name="send_mail[]">
<label>Name2</label>
</div>
(another 2 div tag here)

Laravel AJAX getting all records in one JSON request

i am trying to edit record in my database using ajax, my code is working fine, but i have to mention each column by name, how i can get same result without typing all columns name.
Edit Controller: i am using columns name [efirst,esecond etc] i want to pass everything from database without mentioning name
public function edit($id)
{
$teacher = Teacher::find($id);
return response()->json([
'status' => 'success',
'id' => $teacher->id,
'efirst' => $teacher->efirst,
'esecond' => $teacher->esecond,
]);
}
Edit.js:
jQuery(document).ready(function($) {
$(".table-container").on("click touchstart", ".edit-btn", function () {
$.ajax({
type: "GET",
url: "lists/" + $(this).attr("value") + "/edit",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
beforeSend: function() {
$('#esecond-not-found').remove();
},
success: function (data) {
$("#update-id").val(data['id']);
$("#update-efirst").val(data['efirst']);
$("#update-esecond").val(data['esecond']);
$('#update-form').show();
},
});
});
});
View:
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" name="id" id="update-id">
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<label for="esecond">esecond body</label>
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<div class="">
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
A teacher object can be passed instead of writing every table field
return response()->json([ 'status' => 'success', 'teacher' => $teacher ]);
So in order for this code to work the id of the form needs to match the name of the column
let teacher = Object.entries(data.teacher);
teacher.forEach(item => { $("#"+item[0]).val(item[1]); });
Let's say we have four inputs
<input id="data1" type="text" class="form-control">
<input id="data2" type="text" class="form-control">
<input id="data3" type="text" class="form-control">
<input id="data4" type="text" class="form-control">
and you do this
success: function (data) {
let teacher = Object.entries(data.teacher);
teacher.forEach(item => {
console.log(item)
$("#"+item[0]).val(item[1]);
});
}
the console log gives the following
(2) ["data1", "test1"]
(2) ["data2", "test2"]
(2) ["data3", "test3"]
(2) ["data4", "test4"]
you get an array of arrays that you can loop where the index position 0 is your input id and the index position 1 is your value.

Laravel 5.5 Multilanguage validation

Please tell me, I ran into a problem. There is a site based on Laravel 5.5. The site has a multilanguage (two languages en/ru). For multilanguage I'm using:
dimsav/laravel-translatable
mcamara/laravel-localization
Added language files to the directory resources/lang/ru. The problem is the validation of the form. The site has a feedback form in the modal window, working with ajax (sending and validating), error messages are displayed only in the default language, the default language is en. I tried to send data from the form without the help of ajax, everything works well, messages are displayed in both Russian and English.
reoutes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'PagesController#getProfile')->name('profile');
Route::get('/skills', 'PagesController#getSkills')->name('skills');
Route::get('/portfolio', 'PagesController#getPortfolio')->name('portfolio');
Route::get('/resume', 'PagesController#getResume')->name('resume');
Route::post('/contact', 'PagesController#contact');
});
controller
public function contact(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
if ($validator->passes()) {
Mail::to('mycontactform#mail.ru')->send(new Contact($request));
return response()->json(['success'=>'Message sent successfully!']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
js
$(document).ready(function() {
$(".btn-send-message").click(function(e){
e.preventDefault();
$.ajax({
url: "/contact",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
});
var $success_msg = $(".print-success-msg");
var $error_msg = $(".print-error-msg");
function printSuccessMsg() {
$success_msg.html('Message sent successfully!');
$success_msg.css('display','block');
$success_msg.delay(5000).fadeOut(350);
$('#contact-form')[0].reset();
}
function printErrorMsg (msg) {
$error_msg.find("ul").html('');
$error_msg.css('display','block');
$.each( msg, function( key, value ) {
$error_msg.find("ul").append('<li>'+value+'</li>');
});
$error_msg.delay(5000).fadeOut(350);
}
});
form
<div class="modal-body col-md-8 offset-md-2">
<div class="alert alert-danger print-error-msg" style="display:none">
<strong>Errors:</strong>
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none"></div>
{!! Form::open(['id'=>'contact-form']) !!}
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Your Name">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Your Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
<button type="button" class="btn btn-success btn-send-message"><i class="fas fa-paper-plane"></i>
Send Message <span id="loading" style="display: none;"><img class="loader"
src="{{ asset('images/loading.gif') }}"></span>
</button>
{!! Form::close() !!}
</div>
Use LaravelLocalization::getLocalizedURL() which returns an URL adapted to $locale.
So your ajax code will be.
$.ajax({
url: "{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(),'/contact') }}",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
When you return your response try to use this helper __('translated_string')
To use this helper, you have to create some translate.php file in those folders resources/lang/en and resources/lang/en
For example:
File resources/lang/en/translate.php should contain this array
return [
'success_message' => 'Message sent successfully!',
];
File:
resources/lang/ru/translate.php should contain this array
return [
'success_message' => 'Сообщение успешно отправлено!',
];
For example:
return response()->json(['success'=> __('translate.success_message') ]);
To get some translated string, use dot notation for this helper;
Laravel localization helper

Search a post in Wordpress and load via AJAX

I have this structure in wordpress.
<input type="text" id="search_subject">
<button id="btn_search_subject">Send</button>
<div id="results_search"></div>
<button id="back">Previous</button>
<button id="next">Next</button>
I wanna search a word and via AJAX load the first result in the div #results_search
I lookup some tutorials, but, I didn´t quite understand, some tutorials include all the coode in the functions.php file, and others divide the coding in the ajax.js file.
It could be a search just in the titles of the posts
Here is HTML code
<input class="form-control" placeholder="Search" id="search_posts" name="_posts" type="text" autocomplete="off" value="">
<input type="hidden" value="<?php echo admin_url('admin-ajax.php');?>" id="ajax_url_input">
Here is Jquery Code
jQuery( "#search_posts" ).keyup( function() {
var search_posts = jQuery(this).val();
var ajax_url = jQuery('#ajax_url_input').val();
jQuery.ajax({
type:'POST',
url: ajax_url,
data: {
action: 'search_data',
search_posts: search_posts,
},
beforeSend: function(){
},
success:function(data){
}
});
});
Here is PHP Function for Ajax
function search_data() {
$search = '';
if(isset($_POST['search_posts'])){
$args = array(
'posts_per_page' => -1,
'post_type'=> 'posts',
'post_status'=> 'publish',
's' => $_POST['search_posts']
);
}
$services_data = get_posts( $args );
}
add_action('wp_ajax_search_data', 'search_data');
add_action('wp_ajax_nopriv_search_data', 'search_data');
This code will search text in post title and in post content.

commenting module by ajax not working in laravel 5

i am working on commenting module in my project by ajax. i am getting this error
POST http://127.0.0.1:8000/comments 500 (Internal Server Error)
and the data not post. what i am doing wrong? My route is a resource route and i want to display it without refreshing the page .
Form
<form action="{{route('comments.store')}}" method="post">
{{ csrf_field() }}
<div class="col-md-11 col-sm-11">
<div class="form-group">
<textarea name="comment-msg" id="comment-name" cols="30" rows="1" class="form-control" placeholder="comment here..."></textarea>
<input type="hidden" id="eventID" name="eventID" value="<?php echo $eventData->id; ?>">
<input type="hidden" id="userID" name="userID" value="<?php echo Auth::user()->id; ?>">
</div>
</div>
<div class="col-md-12">
<button type="submit" id="submit-comment" class="btn-primary pull-right">Comment</button>
</div>
</form>
Ajax Call
<script>
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
$( '#submit-comment' ).click(function() {
var formData = {
'message' : $('#comment-msg').val(),
'eventID' : $('#eventID').val(),
'userID' : $('#userID').val(),
};
$.ajax({
type : 'POST',
url : '{{route('comments.store')}}',
data : formData,
dataType : 'json',
encode : true,
success: function (response) {
console.log(response);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
event.preventDefault();
} );
</script>
Controller
public function store(Request $request)
{
$content = $request->input( 'comment-msg' );
$userID = $request->input( 'userID' );
$eventID = $request->input( 'eventID' );
$response=Comment::create([
'user_id' => $userID,
'event_id' => $eventID,
'message' => $content,
]);
return response()->json($response);
}
Route
Route::resource('comments', 'CommentsController');

Resources