ajax datatables can't reload - ajax

i have made function where i can add a row after confirming. the problem is, after submit button, the tables dont reload and show error function alert.actually data success saved and i have to refresh the page so that the table can reload.
here is my ajax jquery code:
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('activity/save')?>";
} else {
url = "<?php echo site_url('activity/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
my controller:
public function save() {
$actype = $this->input->post('actype');
$activity_name = $this->input->post('activity_name');
$project = $this->input->post('project');
$portion = $this->input->post('portion');
$activity = $this->input->post('actid');
$data = array(
'activity_type_id' =>$actype,
'activity_name' =>$activity_name,
'project_id' =>$project,
'portion' =>$portion,
'activity_id' => $activity
);
$this->activity->insertactivity($data);
echo json_encode(array("status" => TRUE));
}
how can i automatically reload only the datatables and show alert success.

Related

Laravel Ajax on Update data getting Success Message on same Page

i am trying to update data using Ajax in Laravel, my data is being updated successfully but when i click on update it's success message is showing on next page, i want it to show message and updated data on same Page without loading page.
Laravel Controller:
public function update(Request $request, $id)
{
$teacher = Teacher::find($id);
$teacher->efirst = $request->efirst;
$teacher->esecond = $request->esecond;
$teacher->save();
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
AJAX function: Update.Js,
jQuery(document).ready(function($) {
$("#update-form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers/" + $('#update-id').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
let teacher = Object.entries(data.teacher);
teacher.forEach(item => { $(`[name=${item[0]}]`).val('item[1]'); });
},
});
});
});
view:
it contains table to show list of teacher with edit, and form under table with update button.
My data is being updated, but i don't want page reload. maybe something to do with append?
if you want to refresh the data
you can make this
var table = $('#tableId');
table.DataTable().ajax.reload();
this command can reload the data,
also in your view,
you can make the button
type="button"
or add to the form
onsubmit="return false;"

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

i got error (Error get data from ajax)

hi i am unable to call my ajax function in codeigniter , below is my script :
whenever i click edit button from my data table i got error (Error get data from ajax) , could u pls help me where i am doing wrong.
<script type="text/javascript">
var save_method;
function edit_question(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
// document.write("test");
//Ajax Load data from ajax
$.ajax({
// document.write("test");
url : "<?php echo base_url('index.php/test_cont/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="question_id"]').val(data.question_id);
// $('[name="cid"]').val("<?php //echo $a; ?>");
$('[name="cid"]').val(data.cid);
$('[name="ques"]').val(data.question);
// $('[name="opa"]').val(data.options);
// $('[name="opb"]').val(data.options);
// $('[name="opc"]').val(data.options);
// $('[name="opd"]').val(data.options);
$('[name="ra"]').val(data.answer);
$('[name="marks"]').val(data.marks);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Questions'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
i have a controller name test_cont , here's code :
public function ajax_edit($id)
{
$data = $this->m->get_by_id($id);
echo json_encode($data);
}
public function question_update()
{
$data = array(
'course_id'=>$this->input->post('cid'),
'question'=>$this->input->post('ques'),
'marks'=>$this->input->post('marks'),
'options' => $options,
'answer' => $this->input->post('ra'),
);
$this->m->question_update(array('question_id' => $this->input->post('question_id')), $data);
echo json_encode(array("status" => TRUE));
}

Ajax response Not working in Codeigniter

I want to show tick.png image on clicking save button when data inserted in database successfully. My view file name is insert_your_committee, model is users_model & controller user
Here is my code of all there files:
My Script of my insert_your_commitee file, All console.log show correct result but success function is not working. What is the problem?
<script>
function save_committee($c_id,$m_id,$start_date){
console.log($c_id);
console.log($m_id);
console.log($start_date);
var mid=$('#irnum'+$start_date).val();
console.log("df"+mid);
var url= "<?php echo site_url("user").'/ref_add';?>";
$.ajax({
url: url,
type: "POST",
dataType:'json',
data: {c_id:$c_id,m_id:$m_id,start_date:$start_date,irnum:mid},
success: function(data){
console.log(data);
$('#'+$start_date).show();
$('#btn'+$start_date).hide();
}
});
}
</script>
My Controller
public function ref_add()
{
$this->load->model('Users_model');
$parms=$this->input->post();
$c_id=$this->input->post('c_id');
$m_id=$this->input->post('m_id');
$s_dateparms=$this->input->post('start_date');
$irnum=$this->input->post('irnum');
$data_to_store = array(
'Cid' =>$c_id,
'Mid' =>$m_id,
'Month' => $s_dateparms,
'Year'=>$s_dateparms,
'Ref_Number' =>$irnum,
);
$params=array();
if ($this->users_model->add_ref($data_to_store)) {
$params['status'] = TRUE;
} else {
$params['status'] = false;
}
$return["json"] = json_encode($params);
echo json_encode($return);
}
And Here is my model
function add_ref($data)
{
$this->db->insert('reference', $data);
$report = array();
$report['error'] = $this->db->_error_number();
$report['message'] = $this->db->_error_message();
if($report !== 0){
return true;
}else{
return false;
}
}
I am not completely sure, but in order to get ajax to work, I had to add return false; after the ajax call in the function.
In my case, I was using ajax for login and backend was in codeigniter.

Ajax Form submit

I am new to Ajax. i wanna submit a form through Ajax and save the data sent to the database.
Something like the Facebook Status update - where text area is disabled and then submited. once its saved in the database it comes back and updates the status message on the top. and again the text area is enabled.
this is my form
<?php echo $form->create('StatusMessage', array('type' => 'post', 'url' => '/account/updateStatus', 'id' => 'updateStatus')); ?>
<?php echo $this->Form->input('id', array('value' => $user['User']['id'],'type' => 'hidden')); ?>
<?php echo $this->Form->textarea('message', array('value' => 'What have you been eating ?')); ?>
Edited: Modified as suggested by 0 RioTera
Cakephp Action
function updateStatus() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax'; //THIS LINE NEWLY ADDED
$this->data['StatusMessage']['pid'] = 0;
$this->data['StatusMessage']['commenters_item_id'] = $this->data['StatusMessage']['item_id'] = $this->User->Item->itemId('1', $this->data['StatusMessage']['id']);
unset($this->data['StatusMessage']['id']);
//debug($this->data);
if($this->User->Item->StatusMessage->save($this->data)) {
return true;
} else {
echo 'not saved';
}
} else {
echo 'no';
}
}
Javascript code
$(document).ready(function () {
var options = {
target: '#output2',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse, // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#updateStatus').submit(function () {
// make your ajax call
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
function showRequest(formData, jqForm, options) {
$('#StatusMessageMessage').attr('disabled', true);
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
alert('shdsd');
}
});
Using jquery and http://jquery.malsup.com/form/ plugin:
$(document).ready(function() {
var options = {
target: '#message', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#updateStatus').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
$('#StatusMessageMessage').attr('disabled', true);
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
}
I didn't try it but I hope it helps you
i hope that this tutorial will help
http://mohammed-magdy.blogspot.com/2010/10/ajaxformsubmitter.html
This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.
$('#myForm').submit(function(e) {
// Catch form submit
e.preventDefault();
$form = $(this);
// console.log($form);
// Get form data
$form_data = $form.serialize();
$form_action = $form.attr('action') + '.json';
// Do ajax post to cake add function instead
$.ajax({
type : "PUT",
url : $form_action,
data : $form_data,
success: function(data) {
swal({
title: "Updated!",
text: "Your entity was updated successfully",
type: "success"
},
function(){
location.reload(true);
});
}
});
});
This is what a simple action would look like in the controller;
public function updateEntity($id = null){
$entity = $this->EntityName->get($id);
$entity = json_encode($this->request->data);
$this->EntityName->save($entity);
}

Resources