In this below code i have 2 dropdown in one dropdown i get course code from course subject table and in another drop relevant subject code for selected course code from course subject table should be displayed. But i cant get the dependent dropdown subject code .Pls any one help me.
Controller:student_site
function search_by_course()
{
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
$html_string .= "</select>";
echo json_encode(array('html_string'=>$html_string));
}
model:student_model
function subject_list($id)
{
//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();
}
view:student_detail_view
<td >
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<div class="subject"></div>
</td>
<script>
$(function(){
$("#course_code_id").live("change keypress",function(){
var id = 0;
id = $(this).val();
if( $(this).val() !==''){
$.post('<?php echo site_url('student_site/search_by_course') ?>',
{
subject_id: id
},function(data){
$(".subject").html( data['html_string']);
},"JSON"
);
}
});
});
</script>
Changes to do:
In view:
<div class="subject">
<select id="subject_code_id"></select>
</div>
<script>
$(function(){
$("#course_code_id").live("change", function(){
var id = $(this).val();
if( id != ''){
$.ajax({
url : '<?=base_url('student_site/search_by_course')?>',
type : 'POST',
data : { 'subject_id' : id },
success : function(resp){
if( resp != "" ){
$("#subject_code_id").html('resp');
}else{
alert("No response!");
}
},
error : function(resp){
alert("Error!");
}
});
}
});
});
</script>
In controller:
function search_by_course(){
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
//$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
//$html_string .= "</select>";
//echo json_encode(array('html_string'=>$html_string));
echo $html_string;
}
Related
I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>
I want when I add a product to the cart and reload the same page, but the problem did not this product.
The controller
public function detail()
{
$data=array('title' =>'Ecommerce Online | Detail Product',
'username' => $this->session->userdata('id'),
'categories' => $this->categories_model->get_categories(),
'details' => $this->categories_model->get_details($this->uri->segment(3)),
'isi' =>'member/detail');
$this->load->view('template_home/wrapper',$data);
}
function addtocart()
{
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('member/detail/'); // this problem
}else{
echo 'true';
}
}
}
I add my models
function validate_add_cart_item()
{
$id = $this->input->post('product_id');
$cty = $this->input->post('quantity');
$this->db->where('productID', $id);
$query = $this->db->get('product', 1);
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $cty,
'price' => $row->price,
'name' => $row->productName
);
$this->cart->insert($data);
return TRUE;
}
}else{
return FALSE;
}
}
I add my view
<?php foreach ($details as $s) { ?>
<div class="col-md-5">
<div class="box text-center">
<img src="<?php echo base_url('upload/'.$s->photo); ?>" width="150px" height="150px">
<br><?php echo $s->productName; ?>
<br><strong>Rp. <?php echo $s->price; ?></strong>
<br>
<?php echo form_open('member/add'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $s->productID); ?>
<?php echo form_submit('add', 'Add'); ?>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
<?php } ?>
Jquery script
<script type="text/javascript">
$(document).ready(function() {
/*place jQuery actions here*/
var link = "<?php echo site_url('member/detail')?>/"; // Url to your application (including index.php/)
$(".detail-product").submit(function(){
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "member/add", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "member/detail", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
});
return false; // Stop the browser of loading the page defined
});
});
</script>
This is problem url: http://localhost/scientificwriting/member/detail/ and productid can not be invoked. Do I need to replace the IF statement on my controller and my jquery?
Please help me thanks
I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>
I want to add comment on pressing enter and want to store it to my database with the specific t_id for it so that i can show it on the page after submission but when i enter text and press enter it does nothing.and i am also suspicious about my add_comment.php fule query because t_id is forgien key in comments table and primary in topics i am at very beginer level in jquery,php and ajax...Any Help will be appreciated.
Here is my Jquery From Send.php
$(document).ready(function(){
$('a').on('click',function(e){
$('#Comments').html('<textarea id="D_Comment" name="D_Comment"></textarea>');
$('a').on('input',function(ev){
$('#Enter_Comments').on('click',function(event){
var d_comnt = $('#D_Comment').val();
if (event.which == 13) {
alert("You Hit Enter");
e.preventDefault();
$.ajax({
url : "ajax/add_comment.php",
type : "POST",
data : {D_Comment : d_comnt},
success : function(data){
console.log(data);
},
error : function(data){
alert(data);
}
});
}
});
// ev.preventDefault();
// return false;
});
//e.preventDefault();
return false;
});
});
and my html from send.php on same page with php showing post from database
<section id="Main_Content">
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$last_id = mysql_real_escape_string($_GET['t_id']);
$sql = "SELECT * FROM Topics WHERE t_id = '".$last_id."'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo "<article>";
// echo $row['t_id'];
echo "<h2>".$row['name']."</h2>"."<br/>";
//echo "<a href='#'>".$row['date']."</a>";
// echo "<a href='#'>".$row['date']."</a>";
echo "<p> Posted on ".$row['date']."</p>"."<br/>" ;
echo "<p>".$row['detail']."</p>"."<br/>" ;
echo "<a href='t_id=".$row['t_id']."' id='Enter_Comments'>"."Enter Comment". "</a>";
echo "</article>";
?>
<div id="Comments"></div>
</section>
and my add_comment.php fiel is
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$d_cmnt = mysql_real_escape_string($_POST['D_Comment']);
$t_id = mysql_real_escape_string($_GET['t_id']);
$sql = "INSERT INTO comments (comment,t_id,date) VALUES('$d_cmnt','$t_id',Now())";
$query = mysql_query($sql);
if ($query) {
echo "Success";
}
else{
echo "Error";
}
?>
I have a form where I add Input fields ( groups ) dynamically.
It is quite a complex form, and a PART can be seen here : FIDDLE
The actual error i get on the consul is :
Error: uncaught exception: query function not defined for Select2 s2id_autogen1
When I have fields already in the form ( the first two for example ) the EDIT and REMOVE button will work just fine .
My problem is that the REMOVE button ( styled input field ) is not working for the dynamically ADDED fields ( actually "appended" by JS and populated from PHP )
NOTE on code: I know the code is a mess :-(. It was inherited and will be cleaned soon.
it was copied and pasted from the HTML output.
The ADD , REMOVE and EDIT are actually styled like buttons ( too long and irrelevant to paste )
The actual source is PHP and it is spanning over multiple files ( so is the JS ) , and thus a bit too complicated to show here .
UPDATE : The code as per popular request :-)
public function show_field_repeater( $field, $meta ) {
global $post;
// Get Plugin Path
$plugin_path = $this->SelfPath;
$this->show_field_begin( $field, $meta );
$class = '';
if ($field['sortable'])
$class = " repeater-sortable";
echo "<div class='at-repeat".$class."' id='{$field['id']}'>";
$c = 0;
$meta = get_post_meta($post->ID,$field['id'],true);
if (count($meta) > 0 && is_array($meta) ){
foreach ($meta as $me){
//for labling toggles
$mmm = isset($me[$field['fields'][0]['id']])? $me[$field['fields'][0]['id']]: "";
echo '<div class="at-repater-block at-repater-block-'.$c.$field['id'].'"><h3>'.$mmm.'
<span class="at-re-remove">
<input id="remove-'.$c.$field['id'].'" class="buttom button-primary" type="submitkb" value="Remove '.$field['name'].'" accesskey="x" name="removek">
</span>';
echo '<script>
jQuery(document).ready(function() {
jQuery("#remove-'.$c.$field['id'].'").on(\'click\', function() {
var answer = confirm("Are you sure you want to delete this field ??")
if(!answer){
event.preventDefault();
}
jQuery(".at-repater-block-'.$c.$field['id'].'").remove();
});
});
</script>';
echo '<span class="at-re-toggle">
<input id="edit-'.$field['id'].'" class="buttom button-primary" type="" value="Edit '.$field['name'].'" accesskey="p" name="editk"></h3>
</span>
<span style="display: none;">
<table class="repeate-box wp-list-table widefat fixed posts" >';
if ($field['inline']){
echo '<tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top">';
}
foreach ($field['fields'] as $f){
//reset var $id for repeater
$id = '';
$id = $field['id'].'['.$c.']['.$f['id'].']';
$m = isset($me[$f['id']]) ? $me[$f['id']]: '';
$m = ( $m !== '' ) ? $m : $f['std'];
if ('image' != $f['type'] && $f['type'] != 'repeater')
$m = is_array( $m) ? array_map( 'esc_attr', $m ) : esc_attr( $m);
//set new id for field in array format
$f['id'] = $id;
if (!$field['inline']){
echo '<tr>';
}
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, $m);
if (!$field['inline']){
echo '</tr>';
}
}
if ($field['inline']){
echo '</tr>';
}
echo '</table></span>
<span class="at-re-toggle"><img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/edit.png';
}else{
echo 'http://i.imgur.com/ka0E2.png';
}
echo '" alt="Edit" title="Edit"/></span>
<img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/remove.png';
}else{
echo 'http://i.imgur.com/g8Duj.png';
}
echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'"></div>';
$c = $c + 1;
}
}
echo '<img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/add.png';
}else{
echo 'http://i.imgur.com/w5Tuc.png';
}
echo '" alt="'.__('Add','mmb').'" title="'.__('Add','mmb').'" ><br/><input id="add-'.$field['id'].'" class="buttom button-primary" type="submitk" value="Add '.$field['name'].'" accesskey="q" name="addk"></div>';
//create all fields once more for js function and catch with object buffer
ob_start();
echo '<div class="at-repater-block">';
echo '<table class="wp-list-table repeater-table">';
if ($field['inline']){
echo '<tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top">';
}
foreach ($field['fields'] as $f){
//reset var $id for repeater
$id = '';
$id = $field['id'].'[CurrentCounter]['.$f['id'].']';
$f['id'] = $id;
if (!$field['inline']){
echo '<tr>';
}
if ($f['type'] != 'wysiwyg')
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, '');
else
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, '',true);
if (!$field['inline']){
echo '</tr>';
}
}
$js_code2 ='<span class=\"at-re-remove\"><input id="remove-'.$c.$field['id'].'" class="buttom button-primary remove-'.$c.$field['id'].'" type="submi7" value="Removevv " accesskey="7" name="remove7"></span>';
if ($field['inline']){
echo '</tr>';
}
$js_code2 = str_replace("\n","",$js_code2);
$js_code2 = str_replace("\r","",$js_code2);
$js_code2 = str_replace("'","\"",$js_code2);
echo $js_code2;
echo '</table><img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/remove.png';
}else{
echo 'http://i.imgur.com/g8Duj.png';
}
echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'" ></div>';
$counter = 'countadd_'.$field['id'];
$js_code = ob_get_clean ();
$js_code = str_replace("\n","",$js_code);
$js_code = str_replace("\r","",$js_code);
$js_code = str_replace("'","\"",$js_code);
$js_code = str_replace("CurrentCounter","' + ".$counter." + '",$js_code);
echo '<script>
jQuery(document).ready(function() {
var '.$counter.' = '.$c.';
jQuery("#add-'.$field['id'].'").on(\'click\', function() {
'.$counter.' = '.$counter.' + 1;
jQuery(this).before(\''.$js_code.'\');
// jQuery("#'.$field['id'].'").append(\''.$js_code2.'\');
// alert(\''.$js_code2.'\');
update_repeater_fields();
});
});
</script>';
echo '<script>
jQuery(document).ready(function() {
jQuery(".remove-'.$c.$field['id'].'").on(\'click\', function() {
var answer = confirm("Are you sure you want to delete this field ??")
if(!answer){
event.preventDefault();
}
jQuery(".remove-'.$c.$field['id'].'").remove();
});
});
</script>';
echo '<br/><style>
.at-inline{line-height: 1 !important;}
.at-inline .at-field{border: 0px !important;}
.at-inline .at-label{margin: 0 0 1px !important;}
.at-inline .at-text{width: 70px;}
.at-inline .at-textarea{width: 100px; height: 75px;}
.at-repater-block{background-color: #FFFFFF;border: 1px solid;margin: 2px;}
</style>';
$this->show_field_end($field, $meta);
}
OK so as you've already been told, the live is deprecated.
Here's the fiddle of the solution: http://jsfiddle.net/y8JFb/2/
Basically give each new div that you dynamically create a unique ID based on your counter, then give data attribute to your remove counter which contains that ID.
Then you have your click handler:
$( document ).on( "click", ".at-re-remove", function( e ) {
$("#"+$(e.target).data("remove")).remove();
$(e.target).remove();
} );