function save ajax error - javascript

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 reloadPage()
{
window.location.reload()
}
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/update_activity')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
$('#myModal').modal('hide');
reloadPage();
$('#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
}
});
}
<button id="btnSave" onclick="save()" class="btn green">
"fa fa-save"> save</button>
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);
redirect("activity/input");
}
after i've clicked button save,alert('Error adding / update data'),but actually after reload page data has saved.
where is code error in my ajax code?

Force a reload from the server.
window.location.reload(true);
When you don't specify true the reload may be from the browser cache if available.
Also, in the controller, redirect("activity/input"); is not the appropriate response to an AJAX request. Try something like this instead.
$this->activity->insertactivity($data);
echo json_encode(array('result' => TRUE));
Your controller code could also be much more concise. Consider this
public function save()
{
$data = array(
'activity_type_id' => $this->input->post('actype'),
'activity_name' => $this->input->post('activity_name'),
'project_id' => $this->input->post('project'),
'portion' => $this->input->post('portion'),
'activity_id' => $this->input->post('actid')
);
//Assuming insertactivity returns TRUE if the insert works and FALSE if not
$results['result'] = $this->activity->insertactivity($data);
echo json_encode($results);
}
You can check the "result" in success function
success: function(data)
{
if(data.result === true)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
} else {
//do something to the DOM to tell about the problem
//which probably means you should add that to your controller's response.
}
},

Related

how do I make delete jquery and then make ajax update a form with php and ajax

I made a form from many tables from a database, like holiday, service and etc.. tables. Holiday is a datepicker and adds dates with jquery and saves when I click the update button. But deleting is not working like this.
I want to delete some holidays with ajax and check some services and then update all of the form with one "update" button. I want to delete using jquery and send the ID of holiday not from the database, then I click on the update button to delete from the database and update all data.
How do I send the ID of the holiday to the server?
My php code for deleting holiday:
if (isset($_POST["holiday_id"])) {
var_dump($_POST);
$holiday_id = $_POST['holiday_id'];
$userid_office = $_POST['userid_office'];
$deleted_holiday = $db->query("delete from holiday where id='$holiday_id' and
$userid_office='$userid_office' ");
var_dump($deleted_holiday);
if ($deleted_holiday == true) {
echo json_encode(['message' => 'successfully deleted', 'status' => 'success']);
die();
} else {
echo json_encode(['message' => 'can not delete', 'status' => 'error']);
die();
}
}
My ajax code for deleting and updating the form:
$(".delete").on('click', function (e) {
e.preventDefault()
var holiday_id=$(this).data("holiday_id");
$('#holiday_'+holiday_id ).remove()
console.log(holiday_id)
return false;
})
$("#scheduleForm").on("submit", function (e) {
e.preventDefault();
var form_data = $(this).serialize();
var url = window.location.pathname + "?mod=schedule&action=schedule_added&ajax=true";
console.log(form_data)
$.ajax({
url: url,
method: "POST",
data: form_data,
success: function (data) {
data = JSON.parse(data)// important because without it show just string
// console.log(typeof data);
if (data.message != null) {
alert(data.message)
} else {
location.reload();
alert("تغییرات باموفقیت انجام شد.")
}
},
error: function (err, err1, err3) {
console.log(err3);
console.log(err1);
}
})
})

I can't update Data in Database : Codeigniter

I can't update data in a database.i don't know what happend.please help me. Display data Press the edit button.But i can not update data on the database.
Controller.php
public function ajax_update(){
$data = array(
'festivalname' => $this->input->post('festivalname'),
'description' => $this->input->post('description'),
'dos' => $this->input->post('dos'),
'doe' => $this->input->post('doe'),
'place_id' => $this->input->post('place_id'),
'pro_id' => $this->input->post('pro_id'),
);
if($this->input->post('remove_fesimg')) // if remove photo checked
{
if(file_exists('upload/festivals/'.$this->input->post('remove_fesimg')) && $this->input->post('remove_fesimg'))
unlink('upload/festivals/'.$this->input->post('remove_fesimg'));
$data['fesimg'] = '';
}
if(!empty($_FILES['fesimg']['name']))
{
$upload = $this->_do_upload();
//delete file
$festival = $this->festivalmodel->get_by_id($this->input->post('fesid'));
if(file_exists('upload/festivals'.$festival->fesimg) && $festival->fesimg)
unlink('upload/festivals'.$festival->fesimg);
$data['fesimg'] = $upload;
}
$this->festivalmodel->update(array('fesid' => $this->input->post('fesid')), $data);
echo json_encode(array("status" => TRUE));
}
Model.php
public function update($where, $data)
{
$this->db->update('tblfestival', $data, $where);
return $this->db->affected_rows();
}
Javascript
function save(){
if(save_method == 'add') {
url = "<?php echo site_url('index.php/festival/ajax_add')?>";
} else {
url = "<?php echo site_url('index.php/festival/ajax_update')?>";
}
// ajax adding data to database
var formData = new FormData($('#form')[0]);/**/
$.ajax({
url : url,
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#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
}
});
I press the save button.but can't update data it's nothing happens.I need to help.Thank you.

500 Internal server error when save proccess using ajax

I want to ask why my codeigniter when add data become error 500 internal server when the save proccess. I dont know anything about this problem please help me all.
This is ajax code in view
function save()
{
$('#btnSave').text('menyimpan...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('edulibs/ajax_add')?>";
} else {
url = "<?php echo site_url('edulibs/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('menambahkan / update data error');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
And this is my controller
public function ajax_add()
{
$this->_validate();
$data = array(
'nama' => $this->input->post('nama'),
'nim' => $this->input->post('nim'),
'pembimbing1' => $this->input->post('pembimbing1'),
'pembimbing2' => $this->input->post('pembimbing2'),
'subyek' => $this->input->post('subyek'),
'judul' => $this->input->post('judul'),
'tanggal' => $this->input->post('tanggal'),
'tautan' => $this->input->post('tautan'),
);
$insert = $this->edulibs->save($data);
echo json_encode(array("status" => TRUE));
}
In order to use site_url() load url helper in your controller first.like this..
$this->load->helper('url');
OR load helper in application/config/autoload.php
And in success function of your ajax use JSON.parse() to parse your json response into object.Like this
success: function(response)
{
var data = JSON.parse(response);//OR var data = eval(response);
if(data.status) //if success close modal and reload ajax table
{
//code here
}
else
{
//code here
}

Load Content after specific time by ajax

I am trying to get data from database without reloading. So I did this
Code In PasteBin
after doing that this is the ajax part for click
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
}
}
});
}
this is the ed_action.php file
$func = new functions();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ed_value = $_POST['ed_value'];
$p_authority_id = $_POST['p_authority_id'];
$user_data = array(
'ed_action' => $ed_value
);
$where_cond = array(
'where' => array('p_authority_id' => $p_authority_id),
'cross_check' => 'and',
'return_type' => 'single'
);
$table_name = 'p_authrity_user';
$update = $func->update($table_name, $user_data, $where_cond);
$ed_action_data = $func->select($table_name, $where_cond);
}
I successfully retrive the data by click. But Now I want when I click on the enable button it will show the disable button without reloading and when click on disable, it should be show the enable button. so what should I do?
Please can you help me?
As I mentioned in comments: In your success function of the ajax request you can just toggle the visibilty of the two buttons.
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
toggleButtons();
}
}
});
}
function toggleButtons(){
var enableBtn = $('button.ed_action.ed_action_enable'); // add class ed_action_enable to button so you can get it here
var disableBtn = $('button.ed_action.ed_action_disable'); // add class ed_action_disable to button so you can get it here
enableBtn.toggle(); // toggles visibility of element
disableBtn.toggle(); // toggles visibility of element
/* shorter code for this:
$('button.ed_action.ed_action_enable').toggle;
$('button.ed_action.ed_action_disable').toggle;
*/
}
For this to work you would need to
1: output both buttons into the html (disable btn hidden)
2: add one more class to the buttons so you can get them easily with jquery

sending a extra parameter in .submit

hello I have a function where I am using ajax to try to do get some value and then submit a php form which looks like this.
/* form-horizontal */
$attributes = array("class" => "form-horizontal", "id" => "register_form");
if (isset($_SESSION['login']))
{
if ($_SESSION['login'] == 'DoBusinessPerformed' || $_SESSION['login'] == 'NormalPerformed') {
echo form_open('myprofile/ManageProcessNew/'.$pathName, $attributes);
} else {
echo form_open('myprofile/RegisterProcessNew/'.$pathName, $attributes);
}
}
else
{
echo form_open('myprofile/RegisterProcessNew/'.$pathName, $attributes);
}
As you can see i have a .$pathname which is the parameter which contains the value 'borrow' and here is the ajax function which I am calling to send this form.
self.checkMangoPayId = function(){
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkMangoPayID/' + auth,
contentType: 'application/json; charset=utf-8',
})
.done(function(data) {
console.log(data);
if(data.mangopay_id == null){
alert("going to save page for mango id");
// here is where I submit the form
$("#register_form").submit();
}else{
self.mangoPayIdCheck(true);
self.showModalAddId();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
what I want to do is in the .submit function add a way to change the value of .$path name and put borrowed instead of borrow.
I tried a lot of ways like .submit(borrowed), but non of those ways work, so basically all I want to send a different value inside pathname to my controller which receives this parameter.
just before your submit you can add a attribute like this
$("#register_form").attr('action',BASEURL + "index.php/bla/bla/borrowed");
and then when you submit it will attach it at the back as parameter.

Categories