I have a table create from datatables, how to change the status field when checkbox clicked, default status is 'before' then when checkbox clicked it update to be 'after'(in database field status), then the table reload..
This dataabs for display table
.....
foreach ($data as $key) {
// add new button, checkbox
$data[$i]['ceklolos'] = '<input type="checkbox" id_data="'.$data[$i] ['status_lolos'].'" class="btn btn-primary btnedit" >';
$i++;
...
How the rest of code, when checkbox in each data clicked that data row update from 'before status' (default database) to be 'after status', after that the table reload..
Thank you, Im using datatable and php
First, add custom data attribute to your checkboxes
<input type="checkbox" data-id="'.$data['id'].'" data-status="'.$data['status'].'" ../>
In your javascript,
// IIFE (Immediately Invoke Function Expressions)
(function (myapp){
myapp(window.jQuery, window, document);
}(function myapp($, window, document){
// $ is now locally scoped
$(function (){
// dom is now ready
var dtTable = $("#sometable").DataTable();
// dom events
$(document).on("change", '.btnedit', function (){
var $this = $(this);
var id = $this.attr("data-id");
var status = $this.attr("data-status");
// send ajax request
$.ajax({
url: 'path-to-your-php-file',
type: 'post',
dataType: 'json',
data: {
id: id,
status: status
},
beforeSend: function (){
// do something here before sending ajax
},
success: function (data){
// do something here
if( data.success ){
// update your table, or any html dom you want here
// if you want to add/remove rows from your dataTable,
// you can refer here
// https://datatables.net/reference/api/row.add()
// https://datatables.net/reference/api/row().remove()
//
}
},
error: function (data){
// do something here if error
// console.warn(data);
}
});
});
});
// The rest of the code goes here
}));
In your PHP file,
<?php
$id = $_POST['id'];
$status = $_POST['status'];
// do your update codes here
//
// after successful update return something so in your ajax you
// will know what happened behind the scene
$response = array('success' => false, 'msg' => 'Some error message');
if( some_update_function_success() ){
$response = array('success' => true, 'msg' => 'Some success message');
}
echo json_encode($response);
Related
Ok so what I'm basically trying to do is sending a form which contains a password (predefined, no DB) through AJAX. In my php file I check the input and I try to return true or false to my JS, but this part fails as I can't manage to access the value. Here is my code:
ajaxRequest.js
// Variable to hold request
var request;
// Bind to the submit event of our form
$(".lockForm").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "assets/php/lockscreen.php",
type: "POST",
data: serializedData,
dataType: 'text',
success: function (data) {
console.log(data.status);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
lockscreen.php
<?php
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass){
if($pass == "SPV" || $pass == "TEACHERS"){
$response = true;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
} else {
$response = false;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
}
}
?>
So far I tried changing the dataType to JSON, but then I got an unexpected end of input error. If I leave it 'text', whenever I try to access the value, I get "undefined". If I only display the console.log, without trying to access any value, I get a success message. I have no idea why though.
call your CheckInput function:
<?php
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass) {
if($pass == "SPV" || $pass == "TEACHERS"){
$result = true;
} else {
$result = false;
}
return array('status' => $result);
}
echo json_encode(CheckInput($pass));
?>
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
}
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 want to delete data from database without refreshing the page. My code is working but after deleteing a product needs to refresh the page. I want something like this
Here is my js code:
<script>
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
$.ajax({
type: "POST",
async: false,
url: "delete_product.php",
data: {
object_id: id
},
dataType: 'json',
success: function(data) {
location.reload();
}
});
}
});
return false;
});
</script>
and the delete_product php code:
<?php
// check if value was posted
if($_POST){
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// set product id to be deleted
$product->id = $_POST['object_id'];
// delete the product
if($product->delete()){
echo "Object was deleted.";
}
// if unable to delete the product
else{
echo "Unable to delete object.";
}
}
?>
Please show me a way to make it!
I see no place where the you're targeting something in the page, but this is what I would use:
<script>
function swapContent(href, url_data, target) {
$.ajax({
type: 'GET',
cache: false,
url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data
success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request
//load more data to "target" value div
target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below
}
})
}
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
swapContent(base_url, url_data, target) //set variables
}
});
return false;
});
</script>
note: because of how much ajax I use, I keep an ajax function by itself
I need to get last insert id from controller to ajax success function......
I want to customize product and when user press add to cart ajax is executed and design is going to insert on database....
And after inserting in database i m getting last insert id.....on insert...
but need last insert id....when user press on add to cart button in hidden field...
here is my Ajax code.
$('#store').click(function(){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
//successfully added..here i am getting last insert id...
// and i want to pass that in hidden variable.....
// on view page.....
}
else {
document.getElementById('succes-message').innerHTML = 'You Design has not Been Saved';
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
});
my CI controller
public function saveData(){
if($this->input->post('action') == 'store') {
$views = $this->input->post('views');
$id = $this->product_model->save($views);
$data = array('cust_id'=>$id);
$this->session->set_userdata($data);
if($id !=''){
header('Content-Type: application/json');
echo json_encode($id);
}
}
}
$this->db->insert_id() returns the last id.
After your insertion operation in model, use following code
$this->db->insert_id();
this will give you id where last insert done.
Documentation