Button Submit Inside Serverside Table Codeigniter - php

I have datatables contain input box and button for each row data, for sure form was added outside table tag, but i have issue while clicking on button submit inside that table, the button did not work well and no appear anything error logs
My Controller.php for displaying row:
public function tagihankost()
{
$list = $this->tagihan->get_datatables();
$data = array();
foreach ($list as $tagih) {
$row = array();
$format = number_format($tagih->harga, '0', '', '.');
$row[] = "<input type='text' value='$tagih->bulan' id='bulan' class='rowtagihan' form='payment-form' readonly>";
$row[] = "<input type='number' value='$format' id='harga' class='rowtagihan' form='payment-form' readonly>";
if ($tagih->status == 200) {
$row[] = "<span class='badge bg-success' style='color:white'>Lunas</span>";
} elseif ($tagih->status == 201) {
$row[] = "<span class='badge bg-warning' style='color:black'>Pending</span>";
} else {
$row[] = "<span class='badge bg-danger' style='color:white'>Belum Bayar</span>";
};
$row[] = "<button id='pay-button'>Pay!</button>";
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->tagihan->count_all(),
"recordsFiltered" => $this->tagihan->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
My View.php :
<div class="card bodycontent">
<div class="card-body">
<div class="tab-pane table-responsive">
<table id="tablekost" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<td>Bulan</td>
<td>Tagihan</td>
<td>Status</td>
<td>#</td>
</tr>
</thead>
<form id="payment-form" method="post" action="<?= site_url() ?>/snap/finish">
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
And the last thing is my JS:
<script type="text/javascript">
$('#pay-button').click(function(event) {
event.preventDefault();
$(this).attr("disabled", "disabled");
$.ajax({
url: '<?= site_url() ?>/snap/token',
cache: false,
success: function(data) {
//location = data;
console.log('token = ' + data);
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type, data) {
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
//resultType.innerHTML = type;
//resultData.innerHTML = JSON.stringify(data);
}
snap.pay(data, {
onSuccess: function(result) {
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result) {
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result) {
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
So what i have missed?

Related

codeigniter ajax cart update quantity

I am new to codeigniter and ajax. I can add item to cart and remove it as well. but when i am trying to update the quantity of the first row it works fine. but if i change the quantity of other rows and when i leave the mouse it updates the price * quanity, but it wont take the quantity what we enterd instead it takes the value of the first row quantity. can anyone please help me out.
view file :
<html>
<head>
<title>Codeigniter Shopping Cart with Ajax JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br /><br />
<div class="col-lg-6 col-md-6">
<div class="table-responsive">
<h3 align="center">Codeigniter Shopping Cart with Ajax JQuery</h3><br />
<?php
foreach($product as $row)
{
echo '
<div class="col-md-4" style="padding:16px; background-color:#f1f1f1; border:1px solid #ccc; margin-bottom:16px; height:400px" align="center">
<img src="'.base_url().'images/'.$row->product_image.'" class="img-thumbnail" /><br />
<h4>'.$row->product_name.'</h4>
<h3 class="text-danger">$'.$row->product_price.'</h3>
<input type="text" name="quantity" class="form-control quantity" id="'.$row->product_id.'" /><br />
<button type="button" name="add_cart" class="btn btn-success add_cart" data-productname="'.$row->product_name.'" data-price="'.$row->product_price.'" data-productid="'.$row->product_id.'" />Add to Cart</button>
</div>
';
}
?>
</div>
</div>
<div class="col-lg-6 col-md-6">
<div id="cart_details">
<h3 align="center">Cart is Empty</h3>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id = $(this).data("productid");
var product_name = $(this).data("productname");
var product_price = $(this).data("price");
var quantity = $('#' + product_id).val();
if(quantity != '' && quantity > 0)
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/add",
method:"POST",
data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
success:function(data)
{
alert("Product Added into Cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter quantity");
}
});
$('#cart_details').load("<?php echo base_url(); ?>shopping_cart/load");
// $(document).ready(function(){
// $("input").blur(function(e){
// e.preventDefault();
// }).blur(function() {
// alert("opo");
// });
// });
$(document).on('mouseleave', '#myqty', function(){
var rowid = $(this).attr("class");
var product_price = $(this).attr("title");
//var proqty = $('#myqty').val();
var fieldId = $(this).attr("class");
var proqty = $('#myqty').val();
alert(proqty);
$.ajax({
url:"<?php echo base_url();?>shopping_cart/update",
method:"POST",
data : {rowid:rowid,proqty:proqty,product_price:product_price},
//data: "rowid="+rowid+"&proqty="+proqty+"&product_price="+product_price,
success:function(data)
{
$('#cart_details').html(data);
}
});
});
$(document).on('click', '.remove_inventory', function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to remove this?"))
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product removed from Cart");
$('#cart_details').html(data);
}
});
}
else
{
return false;
}
});
$(document).on('click', '#clear_cart', function(){
if(confirm("Are you sure you want to clear cart?"))
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/clear",
success:function(data)
{
alert("Your cart has been clear...");
$('#cart_details').html(data);
}
});
}
else
{
return false;
}
});
});
</script>
controller file :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Shopping_cart extends CI_Controller {
function index()
{
$this->load->model("shopping_cart_model");
$data["product"] = $this->shopping_cart_model->fetch_all();
$this->load->view("shopping_cart", $data);
}
function add()
{
$this->load->library("cart");
$data = array(
"id" => $_POST["product_id"],
"name" => $_POST["product_name"],
"qty" => $_POST["quantity"],
"price" => $_POST["product_price"]
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
function load()
{
echo $this->view();
}
function remove()
{
$this->load->library("cart");
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
function clear()
{
$this->load->library("cart");
$this->cart->destroy();
echo $this->view();
}
function view()
{
$this->load->library("cart");
$output = '';
$output .= '
<h3>Shopping Cart</h3><br />
';
echo count($this->cart->contents());
$output .= '
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button>
</div>
<br />
<table class="table table-bordered">
<tr>
<th width="40%">Name</th>
<th width="15%">Quantity</th>
<th width="15%">Price</th>
<th width="15%">Total</th>
<th width="15%">Action</th>
</tr>
';
$count = 0;
foreach($this->cart->contents() as $items)
{
$count++;
$output .= '
<tr>
<td>'.$items["name"].'</td>
<td><input id="myqty" title="'.$items["price"].'" class="'.$items['rowid'].'" type="number" min="1" value="'.$items['qty'].'">
</td>
<td><span id='.$items["price"].'>'.$items["price"].'</span></td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td>
</tr>
';
}
$output .= '
<tr>
<td colspan="4" align="right">Total</td>
<td><span>'.$this->cart->total().'</span></td>
</tr>
</table>
</div>
';
if($count == 0)
{
$output = '<h3 align="center">Cart is Empty</h3>';
}
return $output;
}
function update(){
$this->load->library("cart");
// Recieve post values,calcute them and update
$rowid = $_POST['rowid'];
$price = $_POST['product_price'];
$qty = $_POST['proqty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'qty' => $qty
);
$this->cart->update($data);
echo $this->view();
}
}
<input class="qty_set" name="quantity" data-rowid="your rowid" type="number" value="5">
this will not work "quantity = document.getElementById ("qty_set"). value;"
// use this var quantity = $(this).val();
$(document).on('change', '.qty_set', function(){
var quantity = $(this).val();
var row_id = $(this).data("rowid");
$.ajax({
url:"<?php echo base_url(); ?>Sepet/setliste",
method:"POST",
data:{row_id:row_id, quantity:quantity},
success:function(data)
{
//alert("Güncellendi");
$('#sepetload').html(data);
}
});

Check all checkboxes on the current page only in datatables

I need a solution for this. Here is what I am trying to do. I have a datatable that has some values and check boxes in the first columns. What I need is when I select the check box in the header it should select all the values in the current page only. But all the check boxes of all the pages get selected.
I also want that, When I navigate to another page of the datatable, the check box selections of all the previous page should be unchecked including the check box in the header.
Hear is my code:
<?php if($acl->can('view_article')){ ?>
<table id="articles" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
<tbody>
<?php
foreach($articles as $article) {
$id = $article["id"];
$uid = $article["uid"];
$article_name = $article["article_name"];
$article_file_path = $article["article_file_path"];
$article_category = $article["article_category"];
$article_demographic = $article["article_demographic"];
$article_word_count = $article["article_word_count"];
$intended_month = $article["intended_month"];
$article_created = $article["article_created"];
if(!empty($article_demographic)) {
$article_demographic = implode(", ",$article_demographic);
}
$article_keywords = $article["article_keywords"];
$article_description = $article["article_description"];
$checkbox = in_array($id, $assigned_articles)? " ":"<input type='checkbox' value=".$id." />";
echo "
<tr class='' data-id='$id'>
" ;
if($acl->can('delete_article'))
echo "<td>$checkbox</td>";
if($acl->can('edit_article')){
echo "<td>" . anchor("articles/edit/$id",$article_name.'- '.$article_word_count,"class='notBtn' title=\"$article_description\"") . " </td>";
}else{
echo "<td>$article_name - $article_word_count</td>";
}
echo "
<td>".short_string($article_category)."</td>
<td>".short_string($article_demographic)."</td>
<td> $intended_month </td>
<td align='right'>$article_word_count</td>
</tr>";
}
?>
</tbody>
</table>
<?php } ?>
<script type="application/javascript">
$(document).on( 'init', function ( e, settings ) {
alert( 'Saved page length is: '+ table.state().length );
} );
$(document).ready(function(){
var oTable = $("#articles").DataTable({
"stateSave": true,
"order": [],
"dom": '<"row" <"col-md-12 space" <"datatable-action pull-left"> <"datatable-n pull-right" l > > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
<?php if($acl->can('delete_article')){ ?>
{orderable: false, searchable: false},
<?php } ?>
{"width": "25%" },
null,
null,
{"width": "12%" },
{"width": "10%" },
],
"fnDrawCallback": function( oSettings ) {
$('.popupArticle').viewArticle({
url : '<?=site_url("articles/showArticleInPopup");?>',
title : 'Article Preview',
size : 'lg'
});
}
});
$('#search-inp').on('keyup',function(){
oTable.search($(this).val()).draw() ;
})
if(oTable.state().length != 0)
$('#search-inp').val(oTable.state().search.search);
checkAllCheckbox(oTable);
var deletebtn = '';
<?php if($acl->can('delete_article')){ ?>
var deletebtn = '<i class="fa fa-trash-o"></i>';
<?php } ?>
var assignbtn = '';
<?php if($acl->can('assign_article')){ ?>
var assignbtn = '<i class="fa fa-paperclip"></i>';
<?php } ?>
$("div.datatable-action").html(deletebtn + ' ' +assignbtn);
$('#assignbtn').on('click', function (e) {
e.preventDefault();
eModal.setEModalOptions({loadingHtml : ''});
eModal.iframe('<?= site_url("assignArticles/e/"); ?>', 'Assign Article').then(function (input) {
$('.modal-dialog', window.document).css('width', '80%');
if ($('.modal-footer', window.document).length == 0) {
$('.modal-content', window.document).append('<div class="modal-footer"> </div>');
}
});
});
});
</script>
Here is the code for checkAllCheckbox(oTable);
function checkAllCheckbox(oTable) {
/* Check all in Datatable*/
if ($("#select_all_existent").length != 0) {
var cells = oTable.cells().nodes();
$("#select_all_existent").change(function () {
$(cells).find(":checkbox").prop("checked", $(this).is(":checked"));
});
$(cells).find(":checkbox").change(function(){
if(!$(this).is(":checked")){
$("#select_all_existent").prop("checked", $(this).is(":checked"));
}
else{
if ($(cells).find(":checkbox").length == $(cells).find(":checked").length) {
$("#select_all_existent").prop("checked",true);
}
}
if ($(cells).find(":checked").length > 0) {
$(oTable.table().container()).siblings().find('.help- block').html('');
}
else{
$(oTable.table().container()).siblings().find('.help- block').html('Please select at least one checkbox');
}
});
}
}
Any help on the scenarios that I have mentioned would be appreciated.
In your code made the following changes and try:
change 1: disable sorting of checkbox column
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th data-orderable="false"><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
change 2:
add the following code to script:
$('#articles').on('page.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#articles').on('length.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#select_all_existent').on('change',function () {
checkAllCheckbox(oTable);
});

function wont work after executing ajax load

I have a list of users in my table. At first run it will load using the data from my controller. And I have a remove button function in every row. And then in my remove button I have an ajax load AFTER the successful removal of the user. Now I load the data using ajax. But the problem is the same functionality I have at first wont work anymore. I don't know why.
Here's my code:
Initial load of user from my controller
<table class="table table-bordered table-striped table-hover" id="user-group-list">
<thead>
<tr>
<th></th>
<th>Group Name</th>
<th>Description</th>
<th class="text-center">
<span class="fa fa-plus"></span>
<button class="btn ink-reaction btn-raised btn-danger btn-sm"><span class="fa fa-trash-o"></span></button>
</th>
</tr>
</thead>
<tbody>
<?php if($user_groups) { ?>
<?php foreach($user_groups as $g) { ?>
<tr>
<td class="text-center">
<input type="checkbox" name="group_id[]" value="<?php echo $g['id']; ?>" />
</td>
<td>
<label><?php echo $g['name']; ?></label>
</td>
<td>
<label><?php echo $g['definition']; ?></label>
</td>
<td class="text-center">
<a class="btn btn-icon-toggle btn-primary edit_group" data-id="<?php echo $g['id']; ?>"><i class="fa fa-pencil"></i></a>
<?php if($g['id'] > 2) { ?>
<a class="btn btn-icon-toggle btn-danger remove_group" data-id="<?php echo $g['id']; ?>" data-name="<?php echo $g['name']; ?>"><i class="fa fa-trash-o"></i></a>
<?php } ?>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="4" class="text-center">
<p>There are no user group set</p>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Then in my JS
$('.remove_group').on('click', function(e) {
e.preventDefault();
var group_id = $(this).data('id');
var name = $(this).data('name');
alert(group_id); //wont work anymore after ajax load
bootbox.dialog({
message: "Are you sure you want to remove the group <span class='text-danger'>" + name.toUpperCase() + "</span>",
title: "Notification",
buttons: {
success: {
label: "Yes, remove it",
className: "btn-info",
callback: function() {
$.ajax({
url: "<?php echo site_url('users/user/remove_user_group'); ?>",
data: {group_id: group_id},
dataType: 'json',
type: 'post',
beforeSend: function() {
console.log('Loading...');
},
success: function(d) {
loadUserGroup();
makeToast(d.status, d.toast_info);
},
error: function() {
alert('Error Found!');
}
});
}
},
danger: {
label: "Cancel",
className: "btn-default",
callback: function() {
$(this).modal('hide');
}
}
}
});
});
function loadUserGroup() {
$.ajax({
url: "<?php echo site_url('users/user/load_group_list'); ?>",
dataType: 'json',
beforeSend: function() {
var loader = "<tr>";
loader += " <td colspan='4' class='text-center'><span class='fa fa-spinner fa-pulse fa-3x'></span></td>";
loader += "</tr>";
$('#user-group-list tbody').empty();
$('#user-group-list tbody').html(loader);
},
success: function(data) {
$('#user-group-list tbody').empty();
var group_list = '';
$.each(data.user_groups, function(k, v){
group_list += "<tr>";
group_list += " <td class='text-center'><input type='checkbox' /></td>";
group_list += " <td><label>" + v.name + "</label></td>";
group_list += " <td><label>" + v.definition + "</label></td>";
group_list += " <td class='text-center'>";
group_list += " <a class='btn btn-icon-toggle btn-primary edit_group' data-id='" + v.id + "'><span class='fa fa-pencil'></span></a>";
if(v.id > 2) {
group_list += " <a class='btn btn-icon-toggle btn-danger remove_group' data-id='" + v.id + "' data-name='" + v.name + "'><span class='fa fa-trash-o'></span></a>";
}
group_list += " </td>";
group_list += "</tr>";
//console.log(v.id);
});
$('#user-group-list tbody').html(group_list);
},
error: function() {
alert('Error Occured!');
}
});
}
My ajax load
public function load_group_list() {
$json['user_groups'] = array();
$groups = $this->aauth->get_all_groups();
if(count($groups) > 0) {
foreach($groups as $group) {
$json['user_groups'][] = array(
'id' => $group['id'],
'name' => $group['name'],
'definition' => $group['definition'],
'href' => site_url('users/user/user_group_info?group_id=' . $group['id'])
);
}
}
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json");
echo json_encode($json);
}
Hope the below function fails
$('.remove_group').on('click', function(e) {//your code}
Change that to the below code
$(document).on('click','.remove_group', function(e) {//your code}
It occur because you load the class dynamically and DOM can't identify the element any more

Dependent dropdown values not updating to mysql

In the below there are 2 dropdown course code and subject code .In my update part when i select course code it should populate corresponding subject code from course subject table and update to mysql. My problem is i got the dependent dropdown subject code but it is not updating the value to mysql.
Note:course code and subject code are from course subject table. course code is updating but subject code is not updating.
Controller:student_model
function subject_list()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_subject_records($exam_name,$course_name))
{
$data['all_coursesubject_records'] = $query;
}
$this->load->view('code_view', $data);
}
function manage_student()
{
$data['title']="Manage Student";
//query model to get data results for form
$data=array();
if($query=$this->student_model->get_student_records()){
$data['records']=$query;
}
$editstudent = $this->input->post('editstudent');
if( $this->input->post('editstudent') != false ){
foreach($editstudent as $row_id)
{
$this->form_validation->set_rules("register_number_" . $row_id, "register_number", "required|min_length[2]");
}
}
if ($this->form_validation->run() == FALSE){
$data["message"]="";
//$this->load->view("master_data/view_master_data_header",$data);
//$this->load->view("master_data/view_master_data_nav");
$this->load->view("student_detail_view",$data);
//$this->load->view("master_data/view_master_data_footer");
} else {
// single update - working
if( $this->input->post('editstudent') != false )
{
foreach ($editstudent as $row_id)
{
$data = array(
'register_number' => $this->input->post('register_number_'.$row_id),
'name' => $this->input->post('name_'.$row_id),
'course_code' => $this->input->post('course_code_id'.$row_id),
'subject_code' => $this->input->post('subject_code_id'.$row_id),
);
$this->student_model->update_student_records( $row_id, $data );
redirect('student_site','refresh');
}
$this->session->set_flashdata('dbaction', 'Selected Records have been updated successfully');
}
}
}
model :student_model
function get_subject_records($exam_name,$course_name)
{
//echo "exam_name inside get_subject_records".$exam_name;
//$this->db->select('course_code,subject_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_subject_code_records()
{
$this->db->distinct();
$this->db->select('subject_code');
$query = $this->db->get('coursesubject');
return $query->result();
}
function update_student_records($row_id, $data)
{
$this->db->where('id',$row_id);
$this->db->update('student_table',$data);
}
view:subject_detail_view
<?php
$attributes=array(
'name'=>'updatecustomer',
'id'=>'updatecustomer'
);
echo form_open('student_site/manage_student',$attributes);
?>
<div id="validation_failed">
<?php
echo validation_errors();
?>
<?php $data = array();
if(isset($course_records)){
foreach ($course_records as $row)
{
$data[$row->course_code] = $row->course_code;
} }
?>
<div id="Processy ">
<table class="display table table-bordered table-striped" id='studenttable'>
<thead>
<tr font style='font-size:13px'>
<th> </th>
<th> </th>
<th>Course Code</th>
<th>Subject Code</th>
</tr></thead>
<?php if(isset($records)) : foreach($records as $row) : ?>
<tr >
<td >
<input type=checkbox name="editstudent[]" id="editstudent[]" value="<?php echo $row->id ?>">
</td>
<td >
//drop down course code
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" onChange=" get_subjectdetails112('.$row->id.')" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
<input type="hidden" name="index" id="index" value="<?php echo $row->id; ?>"/>
</td>
<td>
<div id="subject_code_id<?php echo $row->id; ?>" ></div>
<input type="hidden" name="subject_code_id" id="subject_code_id" value="subject_code_id<?php echo $row->id; ?>"/>
</td></tr>
<?php endforeach; ?>
</table>
</div>
<input type="hidden" name="exam_name" id="exam_name" value="<?php echo $row->exam_name; ?>" />
<?php else : ?>
<?php endif; ?>
view: student_update
<script type="text/javascript" charset="utf-8">
function get_subjectdetails112(index) {
alert ("enter firstMAIN");
//var index = jQuery('#index').val();
//alert("index"+index);
var course_name = jQuery('#course_code_id'+index).val();
alert("course_name"+course_name);
//var exam_name = jQuery('#course_name_id>option:selected').text();
var exam_name = jQuery('#exam_name_id').val();
var subject_code = jQuery('#subject_code_id'+index).val();
alert(subject_code);
//var partsArray = exam_name.split('.');
//alert("ssubject_code"+ssubject_code);
//alert("course_name"+course_name);
//alert("exam_name"+exam_name);
jQuery.ajax({
data: 'exam_name='+exam_name+'&course_name=' + course_name,
type: 'POST',
url: 'student_site/subject_list ',
success: function(data){
//alert("inside change");
console.log(data);
//alert ("data"+data);
//for(var j = course_name; j < ssubject_code; j++)
//{
jQuery('#subject_code_id'+index).empty().append(data);
//}
}
});
}
</script>
view:code_view
<?php
if(isset($all_coursesubject_records)){
$subject_data = array();
foreach ($all_coursesubject_records as $row)
{
$subject_data[$row->subject_code] = $row->subject_code;
}
}
echo form_dropdown('subject_code_id', $subject_data,'class="dropdown_class" id="subject_code_id"');
?>
On your student_model (controller) file, try removing the comma here: 'subject_code' => $this->input->post('subject_code_id'.$row_id),
Change to:
$data = array('register_number' => $this->input->post('register_number_'.$row_id),
'name' => $this->input->post('name_'.$row_id),
'course_code' => $this->input->post('course_code_id'.$row_id),
'subject_code' => $this->input->post('subject_code_id'.$row_id));
Not sure though if that will have an effect.

ajax html response can't take effect on link with javascript

I made a form for showing users informations about some presentations. I used ajax cause it should be loaded into a div container and not reloading each time while changing the year.
This is my JavaScript:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: 'include/scripts/select_event.php',
type: 'POST',
data: data,
dataType: 'html',
success: function (select) {
$("#coffee_talk").html(select);
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
ORDER BY
Date ASC
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
/****************************/
/** Output der Tabelle
/****************************/
if ($getID[0] == '') {
echo 'Kein Eintrag vorhanden';
} else {
//Kopf
echo '<table id="table">
<thead>
<tr id="table_head">
<th>Nr.</th>
<th>Datum</th>
<th>Thema</th>
<th>Referent</th>
<th>Begin</th>
<th>Ort</th>
<th>Eintritt</th>
<th>Flyer</th>
<th>Bearbeiten</th>
</tr>
</thead>
<tbody>';
//Mittelteil
$j = 0;
for($i = 0; $i < count($getID); $i++) {
$j = $i + 1;
echo '<tr>
<td class="center">'.$j.'</td>
<td class="center">'.$getDate[$i].'</td>
<td class="center">'.$getTheme[$i].'</td>
<td class="center">'.$getContributer[$i].'</td>
<td class="center">'.$getBegin[$i].'</td>
<td class="center">'.$getPlace[$i].'</td>
<td class="center">'.$getEntrance[$i].'</td>';
if ($getFlyer[$i] == '') {
//Kein Bild vorhanden
echo '<td class="center">Kein Bild vorhanden</td>';
} else echo '<td class="center">'.$getFlyer[$i].'</td>';
echo '<td class="center">
<table id="icons">
<tr>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
</td>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
</td>
</tr>
</table>
</td>
</tr>';
}
//Ende
echo '</tbody>
</table>';
}
}
}
As you can see my outpt is a table. I am using links to make an edit and delete function:
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
and
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
This is my html with the placeholder div:
<div>
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />​​​​​​​​​​​​​​​​​
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
</div>
Now I want to use this JavaScript to do a delete and edit function:
$(".delete_event").click(function() {
alert('hallo');
currentUserID = $(this).data("event-id");
currentTable = $(this).data("table");
$( "#dialog_delete_event" ).dialog( "open" );
});
$( '#dialog_delete_event' ).dialog({
autoOpen: false,
resizable: false,
height: 170,
modal: true,
buttons: {
'Ja': function() {
document.location = "index.php?section=event_delete&id=" + currentUserID +"&table=" + currentTable;
$( this ).dialog( 'close' );
},
'Nein': function() {
$( this ).dialog( 'close' );
}
}
});
My problem is that the click_function (defined in the links) is not working. I Found out that the ajax form response is not written into the html code. Bet that this is the problem. What can I do to give the links a working click function?
im not sure due to your code's size but this:
$(".delete_event").click(function() {
should be
$(".delete_event").live("click",function() {
because you dynamically create html; the "live" works with that.
Like #Albit, not really sure what your question is, assuming the ajax is working correctly, and the results are visible on the screen, instead of using:
$(".delete_event").click(function() {
try
$(".delete_event").live("click", function() {
This means that elements that satisfy the selector after page load will still trigger an event.
i don't know if i undestood your problem correctly but just use the onclick event in the html tag of the anchor and you will be ok . if this is not the correct answer plese ignore me

Categories