populating dropdown based in first selection - ajax

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

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');
}
}
...

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

How to change 'active/inactive status of user' through ajax?

I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page.
I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status.
//view
<script>
$(document).ready(function()
{
$('#academicTable_wrapper').hide();
$('#studentTable').DataTable();
showStudents();
function showStudents()
{
$('#submitBtn').on('click',function(){
var courseId = $('#courseId').val();
var classId = $('#classId').val();
$.ajax({
type : 'POST',
url : "<?php echo base_url();?>Student/getStudentsList",
// async : true,
data : {courseId:courseId,classId:classId},
dataType : 'json',
success : function(data){
//alert(data);
var html = '';
var i;
for(i=0; i<data.length; i++){
var studentId = data[i].studentId;
if(data[i].status == 1)
var status = "Approved";
else if(data[i].status == 0)
var status = "Pending";
else
var status = "Left";
html += '<tr>'+
'<td>'+data[i].studentId+'</td>'+
'<td>'+data[i].studentName+'</td>'+
'<td>'+data[i].studentPhoneNum+'</td>'+
'<td>'+data[i].created_on+'</td>'+
'<td id="changeStatus">'+status+'</td>'+
'<td>'+
'View'+
' '+
'<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+
' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#studentTable').DataTable().destroy();
$('#showData').html(html);
$('#studentTable').DataTable();
$('#academicTable_wrapper').show();
}
});
});
}
$(document).on('click','#activateBtn',function()
{
var id = $(this).data('id');
var status = $(this).data('status');
$.ajax({
method: 'POST',
url: "<?php echo base_url();?>Student/approveStudent",
data:{id:id,status:status},
success : function(data)
{
alert(data);
$('#changeStatus').text('');
if(data == 0)
{
showStudents();
$('#changeStatus').html('Inactive');
}
else{
showStudents();
$('#changeStatus').html('Approv');
}
},
error:function(data)
{
console.log(data);
}
},1000);
});
});
</script>
//controller
function approveStudent()
{
$id = $this->input->post('id');
$status = $this->input->post('status');
$col = 'id';
$query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail);
if($query){
$result = $this->Admin_model->getData($col,$id,$this->studentDetail);
}
$status = 1;
if ($result[0]->status == 0)
{
$status = 0;
}
echo $status;
}
I expect whenever I click activateBtn the status should change in database and also in datatable.

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

JQuery Ajax POST 500 Interval error

I have an error 500 (Internal Server Error), I dont know what is the problem
m.ajaxTransport.a.send # jquery.min.js:4
(anonymous function) # add:198
fichier javascript:
$("#addItem").on('click',function(e){
e.preventDefault();
var id_produit = parseInt($("#produit_id option:selected").val());
var prix = parseFloat($('#prix_produit').val());
var remise = parseFloat($('#remise_produit').val());
var qte = parseInt($('#count_produit').val());
var id_facture = <?php echo($count_id); ?>;
var data = [];
data = {
FacturesProduit: {
facture_id : id_facture,
produit_id : id_produit,
prix : prix,
remise : remise,
quatite : qte
}
};
console.log(data);
var url = <?php echo $this->Html->url(array('controller' => 'facturesproduits' , 'action' => 'ajout_produit')); ?>;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (result) {
console.log(result);
}
});
});
Action :
public function ajout_produit() {
$message = 'error';
if ($this->request->is('ajax')) {
$data = $this->request->data;
if ($this->FacturesProduit->save($data)) {
$message = 'success';
}
}
echo json_encode($message);
die();
}
thanks

Resources