How to Ajax with select2 auto fill another input field - ajax

please your help ,how to auto fill with ajax + select2 using medoo framework database to autofill another input in same form .
this my ajax code :
$('.matrix').select2({
ajax: {
url: "index.php",
dataType: 'json',
data: function (params,page) {
return {
q: params.term, // search term
qa: 'matrix'
};
},
processResults: function (data,params) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
//cache: true,
},
minimumInputLength: 3,
placeholder: "<?php _e('Please Select'); ?>",
});
Please your advice .

This my search data :
case "matrix":
$searchstring = "";
if(isset($_GET['q'])) $searchstring = $_GET['q'];
if($searchstring != "") {
$items = $database->select("tbl_matrix", "*", [ "OR" => [
"bc_name[~]" => $searchstring
]]);
} else {
$items = $database->select("tbl_matrix", "*");
}
$results = array();
$results[0]['id'] = 0;
$results[0]['text'] = __('None');
$i = 1;
foreach($items as $item) {
$results[$i]['id'] = $item['id'];
$results[$i]['text'] = $item['bc_code']." ".$item['bc_name'];
$i++;
}
echo json_encode($results);
break;

Related

Ajax submission triggers Error = True by default even at success

Laravel ajax submission.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '{{URL::to('expense_bill/store2')}}',
method: 'POST',
data: $("#expense_create").serialize(),
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
},
error: function (xhr) {
$('#validation-errors').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
});
},
});
});
Controller:
public function store2(Request $request)
{
if($request->ajax()){
//return response()->json($request);
$validator = Validator::make($request->all(), [
'supplier' => 'required',
]);
if ($validator->fails()) {
$returnArray['error']=true;
$returnArray['err_msg']=json_decode(json_encode($validator->errors()), true);
return $returnArray;
}
if ($validator->passes()) {
$request->merge(['total' => $request->total*100]);
$request->merge(['tax_value' => $request->tax_value*100]);
$expensebillheader = ExpenseBillHeader::create($request->all());
$expense_bill_no = $expensebillheader->id;
$count = $request->input('count');
for ($i = 0; $i <= $count; $i++){
//checks if input with this name exists (incase if any middle row was deleted)
if (isset($request->input('amount')[$i]))
{
$line = new ExpenseBillBody;
$line->bill_no = $expense_bill_no;
$line->description = $request->input('description')[$i];
$line->amount = $request->input('amount')[$i];
$line->account = $request->input('account')[$i];
$line->save();
}
};
$successArray = ['success'=>'true','msg'=>"Expnese No".$expense_bill_no." Created"];
return response()->json($successArray);
}
}
}
When validator fails, it's all fine. When validator passes it is supposed to give success=" true" message. But along with that it also gives error="true" as well. Not sure what am I doing wrong. See in the screenshot, the highlighted portion should not come.
Larave returns correct response. You have error here
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
}
...
if(data['success'] = true) and if(data['success'] = true) isn't comparasion, these are assigning values
Try to write comparasion operators ==
success:function(data){
console.log(data)
if(data['success'] === true){
}
if(data['error'] === true){
//Clear Valdiation Errors
console.log('hi');
}
}
...

codeigniter foreach not displaying all records in table

Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached

populating dropdown based in first selection

My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced

Laravel 5 getClientOriginalExtension() returns empty string

I checked if file exists using Input::hasFile('File'), and it returns true and successfully got file's binary.
But Input::file('File')->getClientOriginalExtension() returns empty string.
Here's my controller
public function ConfirmWrite()
{
if (!Session::has('id')) {
return '0:Please log in.';
}
$Data = Request::all();
$Data['uid'] = Session::get('id');
$Data['mid'] = 0;
var_dump(Input::file('File')->getClientOriginalExtension());
return '1';
if (Input::hasFile('File')) {
$file = Input::file('File');
$rules = ['File' => 'mimes:jpeg,bmp,png,jpg|max:10000'];
$validator = Validator::make(['File' => $file], $rules);
if ($validator->fails()) {
return '0:Check your File.';
}
$Data['Thumbnail'] = $file->getClientOriginalExtension();
$destinationPath = 'images/post/thumbnail/';
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
$upload_success = $file->move($destinationPath, $Content . '.' . $Data['Thumbnail']);
echo "asdfasdfasdf : ".$Data['Thumbnail'];
if ($upload_success) {
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 320, 'small');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 700, 'medium');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 1920, '');
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
} else {
return '0:Somethings wrong';
}
} else {
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
}
}
And below code is Front-end Ajax code.
var fData = new FormData;
GlobalVar.Thumbnail == '' ? '' : fData.append('File', DataURLtoBlob(GlobalVar.Thumbnail));
fData.append('Title', $('.contents-details').find('h1').html());
fData.append('Subtitle', $('.contents-details').find('h2').html());
fData.append('Content', $('#post-editor').froalaEditor('html.get'));
fData.append('Align', EditorAlign);
fData.append('Tag', Tag);
fData.append('Share',GlobalVar.FBShare);
$.ajax({
url: '{{ URL::to('/post/write') }}',
type: 'post',
processData: false,
enctype: "multipart/form-data",
contentType: false,
cache: false,
data: fData,
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function (result) {
var Check = $.trim(result).split(':');
$('.submit-loading').css('display', 'none');
if (Check[0] == '1') {
checkUnload = false;
location.href = '{{ URL::to('post') }}/' + Check[1];
} else {
console.log(result);
Warning(Check[1]);
}
},
});
I can't find where is bug code and mistake I made. Please help me. This make me mad.
The getClientOriginalExtension method returns the extension of the actual file uploaded some-image.pdf, this is not considered a safe value. Instead you could best use guessExtension.
The guessExtension method uses the actual mime type and returns the related file type.

Select2 not returning any data, just display searching

i'm using codeigniter and select2 plugin for displaying my data.. but i have a problem, that plugin not display anything, just display searching... there is my code
/*------------- JS -----------------*/
$("‪#‎nm_peg‬").select2({
placeholder: "Masukkan Nama Pegawai",
width:'element',
ajax : {
url : "<?php echo site_url('pegawai/getAllData'); ?>",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
this is my controller
/*-------------- Controller ---------------*/
public function getAllData()
{
$this->load->model('pegawaimodel');
$d = $this->pegawaimodel->get_all_pegawai();
$rows = array();
foreach ($d as $a) {
$rows[] = $a;
}
header('Content-Type:application/json');
return json_encode($d);
}
and this is my model.
/*--------------Model-----------------*/
public function get_all_pegawai()
{
$this->db->select('peg_id, peg_nama');
$this->db->from('master_pegawai');
$query = $this->db->get();
return $query->result();
}
thank's for any help..

Resources