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
}
Related
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.
I am insert the data in mysql database using ajax on submitting this error will appaer .I am making this
in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
// if (save_method == 'add') {
url = "http://[::1]/sms/sms/forms/1";
// } else {
// url = "";
//// }
var radio=$('#radio').val();
var st_id=$('#st_id').val();
var branch_type=$('#branch_type').val();
bname=$('#bname').val();
bcode=$('#bcode').val();
baddress=$('#baddress').val();
var bcity=$('#bcity').val();
var zcode=$('#zcode').val();
var bstates=$('#bstates').val();
var bcountry=$('#bcountry').val();
var bpno=$('#bpno').val();
var bemail=$('#bemail').val();
var bweb=$('#bweb').val();
var Latitude=$('#Latitude').val();
var Longtitude=$('#Longtitude').val();
var noted=$('#noted').val();
var addedby=$('#addedby').val();
// ajax adding data to database
$.ajax({
type: 'ajax',
data: {st_id: st_id, branch_type: branch_type, bname: bname, bcode: bcode, baddress: baddress,
bcity: bcity, zcode: zcode, bstates: bstates, bcountry: bcountry, bpno: bpno, bemail: bemail,
bweb: bweb, Latitude: Latitude, Longtitude: Longtitude, noted: noted, addedby: addedby},
url: url,
method: 'post',
asysc: false,
dataType: 'json',
success: function (data) {
if (data.status) //if success close modal and reload ajax table
{
}
else {
}
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + textStatus + errorThrown);
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
//
}
});
my php code
$submit['sys_t_id']=$this->input->post('st_id');
$submit['t_id']=$this->input->post('branch_type');
$submit['name']=$this->input->post('bname');
$submit['code']=$this->input->post('bcode');
$submit['address']=$this->input->post('baddress');
$submit['city']=$this->input->post('bcity');
$submit['zip']=$this->input->post('zcode');
$submit['state']=$this->input->post('bstates');
$submit['country']=$this->input->post('bcountry');
$submit['contact_no']=$this->input->post('bpno');
$submit['email']=$this->input->post('bemail');
$submit['web']=$this->input->post('bweb');
$submit['latitude']=$this->input->post('Latitude');
$submit['longitude']=$this->input->post('Longtitude');
$submit['note']=$this->input->post('noted');
$submit['addedby']=$this->input->post('addedby');
$submit['addedon']=date('Y-m-d:H-m-s');
$insert = $this->Smsmodal->insert('branch_info',$submit);
echo json_encode(array("status" => TRUE));
I think you have server error! Use console.log(data) in you success function for see server output.
I want to get data with ajax and jquery. But i get thhis error and i dont know how to fix it.
VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10
This is my code.
Model
public function GetBloodCatById($id)
{
$this->db->from('tbl_blood_cat');
$this->db->where('id_blood_cat',$id);
$query = $this->db->get();
return $query->row();
}
Controller
public function ajax_edit($id)
{
$data = $this->Blood->GetBloodCatById($id);
echo json_encode($data);
}
View
function edit_blood(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('Home/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
contentType: 'application/json',
success: function(data)
{
$('[name="id_blood_cat"]').val(data.id_blood_cat);
$('[name="catName"]').val(data.category);
$('#myModalBloodCat').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Blood Cat'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
This is data that will be get
{"id_blood_cat":"1","category":"Plasma","createBy":"nicky","updateBy":null,"createAt":"2017-05-11 18:30:09","updateAt":"2017-05-11 18:30:09","flag":"1"}
I had been strugle with this for hours. Please help me thx.
wrapping json in array is always good choice.Here i have modified your function little
public function ajax_edit($id)
{ $res = array();
$data = $this->Blood->GetBloodCatById($id);
$res = $data;
echo json_encode($data);
}
and ajax success handler is like
........
success: function(data)
{ response = $.parseJSON(data);
$.each(data, function (i, item) {
$('[name="id_blood_cat"]').val(response.id_blood_cat);
$('[name="catName"]').val(response.category);
}
$('#myModalBloodCat').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Blood Cat'); // Set title to Bootstrap modal title
},
........
Reomve php tag and try to set url like this
url : "/Home/ajax_edit/?id=" + id,
Try: url: 'file:///Home/ajax_edit/?id='+id
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.
}
},
I am making a LIVE UPDATE in CodeIgniter and it is almost working.
Just one little issue: When I click the button it also appears my navigation inside the "responds" box which is very strange.
And when I refresh the page it is removed and the record is there.
Here is an image to explain what I mean
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
//##### Add record when Add Record Button is click #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val() ==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('admin/dashboard/index'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response) {
$("#responds").append(response);
},
error:function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
</script>
EDIT:
HERE IS THE CONTROLER
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load libraries
$this->load->library('ion_auth');
$this->load->library('parser');
// Load models
$this->load->model('note_model');
// Load helpers
$this->load->helper('date');
// Set error delimiters
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
}
public function index()
{
// Check if user is loged in
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
else
{
// Create notes object
$notes = new Note_model();
// Order the notes by date post
$notes->order_by('date_post', 'desc')->get();
$recent_notes = array();
foreach ($notes as $note)
{
$single_note = array
(
'id' => $note->id,
'note_text' => $note->note_text,
'date_post' => $note->date_post,
);
array_push($recent_notes, $single_note);
}
// Get the user id as an object
$getinfo = $this->ion_auth->user($this->session->userdata('user_id'))->row();
// Create a new note
$createNote = new Note_model();
$createNote->note_text = $this->input->post('content_txt');
$created = date('Y-m-d H:i:s');
$createNote->date_post = $created;
// Validation rules
$rules = $this->note_model->rules;
$this->form_validation->set_rules($rules);
$data = array
(
'admin_content' => 'admin/dashboard',
'notes' => $recent_notes,
'username' => $getinfo->{'first_name'} . ' ' . $getinfo->{'last_name'},
);
if ($this->form_validation->run() == FALSE)
{
$this->parser->parse('admin/template_admin', $data);
}
else
{
$createNote->save();
redirect('admin/dashboard');
}
}
}
The problem is the action you are calling.
It seems admin/dashboard/index outputs the navigation as well as the data you want to display.
You should post to an action that ONLY displays the data you require, and nothing else