Display none not working with dynamically Id using Ajax - javascript

I am working with jquery and i am trying to enable/disable using ajax jquery,Function working but showing result after
page refresh,ajax response condition is not working(dynamically),
Here is my html
<td>
<?php if(($ban->status)==1) {?>
<button type="button" class="btn btn-warning" id="disable <?php echo($ban->id); ?>" onclick="enable(<?php echo($ban->id); ?>)">Disable</button>
<?php }else{ ?>
<button type="button" id="enable <?php echo($ban->id); ?>" class="btn btn-success" onclick="enable(<?php echo($ban->id); ?>)">Enable</button>
<?php }?>
</td>
Here is my ajax
<script type="text/javascript">
function enable(id) {
var id = id;
alert(id);
$.ajax({
type: 'POST',
url: "<?php echo base_url('upload_controller/enable');?>",
data: {'id': id},
cache: false,
dataType: "html",
async: false,
success: function(data){
alert(data);
$('#response').html(data);
if (jQuery.trim(data) == "disabled")
{
document.getElementById(`enable ${id}`).style.display = "none";
document.getElementById(`disable ${id}`).style.display = "block";
}
else // if status enabled ( query working fine)
{
document.getElementById(`disable ${id}`).style.display = "none";
document.getElementById(`enable ${id}`).style.display = "block";
}
}
});
}
</script>
Here is my controller
public function enable(){
$id=$this->input->post('id');
$sql = "SELECT status from banner WHERE id=$id";
$querys=$this->db->query($sql);
$rtnArr = $querys->row_array();
//echo "<pre>";print_R($rtnArr);
$status=$rtnArr['status'];
//die();
if($status=="1")
{
$sql = "UPDATE banner SET status=0 WHERE id=$id";
$query=$this->db->query($sql);
echo "disabled";
die();
}
else
{
$sql = "UPDATE banner SET status=1 WHERE id=$id";
$query=$this->db->query($sql);
echo "enabled";
}
}

Here's an example to show how you can use a single button and toggle it's style and text. I did it this way thinking you may have multiple buttons to toggle, though it works fine with one. TO keep it flexible, we put the status and the id into data-attributes. You can test it here, and it will show the toggle, but to test it with your code, remove the part that is commented for you to remove.
$(document).ready(function() {
$('.btn-enable').each(function() {
setButton($(this), +$(this).attr('data-status'))
})
$('.btn-enable').click(function() {
// remove the next 2 lines for your actual code. This is for the snippet test
setButton($(this), +$(this).attr('data-status') === 1 ? 0 : 1)
return
$.ajax({
type: 'POST',
url: "<?php echo base_url('upload_controller/enable');?>",
data: {
'id': $(this).data('id')
},
cache: false,
dataType: "html",
async: false,
success: function(data) {
//alert(data);
$('#response').html(data);
if (jQuery.trim(data) == "disabled") setButton($(this), 0)
else setButton($(this), 1)
}
})
})
})
function setButton(button, status) {
console.log(status)
let cl = status ? 'btn-warning' : 'btn-success';
let text = status ? 'Disable' : 'Enable';
$(button).removeClass(['btn-warning', 'btn-success']);
$(button).addClass(cl);
$(button).attr('data-status', status);
$(button).text(text)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<button type="button" class="btn btn-enable" data-id='<?php echo($ban->id); ?>' data-status="<?php echo($ban->status); ?>"></button>

Related

JQuery Event executed only once

I am trying to trigger a JQuery Ajax event for a bunch of buttons.
Here is the code in index.php file :
<?php
foreach($data as $d) {
$myid = $d['id'];
$mystatus = $d['status'];
?>
<div class="input-group-prepend">
<button id="submitbtn" type="button" class="myupdatebtn btn btn-success" data-id="<?php echo $myid; ?>" disabled>Finish Task</button></div>
<li class="nav-item">
<a class="nav-link clickable blueMenuItem" id="nav-location" data-id="<?php echo $d['id']; ?>">
<i class="nav-icon fas <?php echo $d['icon']; ?>"></i>
<p>
<?php echo $d["title"];
if ($d['type'] == "task") { ?>
<span id="updatemsg-<? echo $d['id'];?>" class="right badge <?php if($mystatus == "TERMINATED"){echo "badge-success";} else {echo "badge-danger";}?>"><?php setTerminated($conn, $myid)?></span>
<?php } ?>
</p>
</a>
</li>
<?php } ?>
Where the menu items (titles, status and icons) are extracted from a MySQL Database.
Here is the JAVASCRIPT (JQUERY) file with AJAX call :
$('.myupdatebtn').on('click', function() {
var id = $(this).data('id');
$.ajax({
url: 'includes/updatestatus.php',
type: 'POST',
data: {id:id},
dataType: 'html',
success: function(data)
{
if (data)
{
$('#submitComment').attr("disabled", true);
$('#customComment').val("");
$('#updatemsg-'+id).html("TERMINATED").removeClass('badge-danger').addClass('badge badge-success');
console.log(id);
}
else
{
$('#customContent').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#customContent').html("ERROR MSG:" + errorThrown);
}
});
});
This is the code for the updatestatus.php file :
<?php
include("db.php");
$id = $_POST['id'];
$query = "UPDATE mytable SET status='TERMINATED' WHERE id='$id'";
mysqli_query($conn, $query);
?>
As you can read from the code, when the button is clicked, it will be disabled and the input will be empty. The problem is that this code runs only once, after that the button will not updated the DATABASE and the DOM will not be updated (only after refresh and press the button again).
Is there a way to terminate the JQuery event after each iteration (Button pressed for every menu item) and make it available again to be executed?
You said you have "bunch of buttons.", I see only 1 in your code.
But if you have bunch of buttons with same class but different id, this code will work.
$('.myupdatebtn').each(function(){
$(this).on('click', function() {
var id = $(this).data('id');
$.ajax({
url: 'includes/updatestatus.php',
type: 'POST',
data: {id:id},
dataType: 'html',
success: function(data)
{
if (data)
{
$('#submitComment').attr("disabled", true);
$('#customComment').val("");
$('#updatemsg-'+id).html("TERMINATED").removeClass('badge-danger').addClass('badge badge-success');
console.log(id);
}
else
{
$('#customContent').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#customContent').html("ERROR MSG:" + errorThrown);
}
});
});
})
Give appropriate ids to buttons, so that your updatestatus.php works correctly.
$('.mybtn').each(function(){
$(this).click(function(){
alert("You clicked the button with id '"+this.id+"' call ajax do whatever");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Bunch of buttons right?</h2>
<button id="1" class="mybtn">btn1</button><br/>
<button id="2" class="mybtn">btn1</button><br/>
<button id="3" class="mybtn">btn1</button><br/>
<button id="4" class="mybtn">btn1</button><br/>
<button id="5" class="mybtn">btn1</button><br/>
I couldn't understand what you meant by this 'Is there a way to terminate the JQuery event after each iteration (Button pressed for every menu item) and make it available again to be executed?', but as I know you need an active event listener, which triggers all the time button is clicked?
And one more thing I noticed, you are using if(data){//code} but what data?, you are not returning anything from php file, return something.
<?php
include("db.php");
$id = $_POST['id'];
$query = "UPDATE mytable SET status='TERMINATED' WHERE id='$id'";
if(mysqli_query($conn, $query)) echo "1";
else echo "2";
?>
Then use if(data === 1) {//do task} else if(data === 2){//Do else task}.

How to get ajax response using custom attribute in php loop

I am working with ajax with php,I have following buttons in loop,I just want to
show/fetch data(number) on correct place/div using "attr" in jquery but not working in my side
Here is my button in loop
<?php
foreach //
<button class="btn likebutn_r" data-datac="1" data-datacw="<?php echo $WalletAddress; ?>" data-datacr="<?php echo $rev->id; ?>" data-datacoin="<?php echo $rev->coin_id; ?>" data-datasymbol="<?php echo $rev->symbol; ?>" id="show<?php echo "1";?>" value="1" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<div id="<?php echo $rev->id; ?>">12(dynamic)</div>
endforeach//
Here is my ajax code,How can i get data using custom attribute (via pass ReviewId)? Thanks in advance
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function (e) {
var vote = $(this).data('datac');
var review = $(this).data('datacr');
var CoinId = $(this).data('datacoin');
var symbol = $(this).data('datasymbol');
var WalletAddress = $(this).data('datacw');
var datacrp = $(this).data('datacrp');
$('#' + review).hide();
e.preventDefault();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>main/AddVote',
data: {
vote: vote,
review: review,
CoinId: CoinId,
symbol: symbol,
WalletAddress: WalletAddress
},
success: function (data) {
alert(data);
$('#' + review).html(data);
}
});
});
});
</script>
Hope this code help you.
*Reminder the js code below have to implement inside the php file so the Post url ajax will get the value.
$('body').on('click', '.btn', function(e){
var allData = {
"vote": $(this).data('datac'),
"review": $(this).data('datacr'),
"CoinId": $(this).data('datacoin'),
"symbol": $(this).data('datasymbol'),
"WalletAddress": $(this).data('walletaddress'),
}
e.preventDefault();
$.ajax({
type: 'POST',
url:'test.com',
data: allData,
success: function(data) {
$(this).attr('data-datac', data['vote']);
$(this).attr('data-datacr', data['review']);
$(this).attr('datacoin', data['CoinId']);
$(this).attr('data-datasymbol', data['review']);
$(this).attr('data-datacoin', data['review']);
$(this).attr('data-datasymbol', data['symbol']);
$(this).attr('data-walletaddress', data['WalletAddress']);
}
});
});
<button
class="btn likebutn_r"
data-datac="1"
data-datacw="teste"
data-datacr="asdfasf"
data-datacoin="asdfasdf"
data-datasymbol="asdfasdf"
data-datacrp="asfsa"
id="31"
data-walletaddress="dsaf"
value="1"
type="submit">Hello</button>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>

Inactive and active PHP MySQL

Having problem to change the state if its active or inactive everytime I clicked one of them nothings happened.
This is my code on ajax.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
var status = ($(this).hasClass("btn-success")) ? '0' : '1';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg)){
var current_element = $(this);
url = "ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:$(current_element).attr('data'),status:status},
success: function(data)
{
location.reload();
}
});
}
});
</script>
my php code ajax.php
<?php $db= new mysqli('localhost','root','password','dbname');
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE user SET status='$status' WHERE id='$id'");
echo 1;
?>
this is my code for displaying it, on this part everything works fine, when the value are 0 it will display inactive and 1 for active, however when clicking the status theres nothing happen only the notification and reload the page.
<td><i data="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' : 'Inactive'?>
</i></td>
Try to configure your code to:
$(document).on('click','.status_checks',function(){
var status = '1';
var msg = 'Activate';
if($(this).hasClass("btn-success")){
status = '0';
msg = 'Deactivate';
}
if(confirm("Are you sure to "+ msg)){
var id= $(this).data('id');
url = "/ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:id,status:status},
dataType: "json",
success: function(data)
{
console.log(data);
location.reload();
}
});
}
});
<?php $db= new mysqli('localhost','root','password','dbname');
$user_id=$_POST['id'];
$newStatus=$_POST['$status'];
$sql = "UPDATE user SET status=".$newStatus." WHERE id=".$user_id."
";
if($db->query($sql) === TRUE){
echo json_encode(1);
}else{
echo json_encode(0);
}
?>
<td><i data-id="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' :
'Inactive'?>
</i></td>

Sent value and show output when select tag change

I new in term of using jQuery.
I practice using native php ajax, but for this time I need to learn jQuery for the current technology and demand.
I sent "types" value method POST to other page (ajaxInfo.php) when the tag change.
After the select tag change, it should show the result at <div id="showList"> that come from database (MySQL). But nothing happen.
Below are the source code.
Body
<select id="form-types" class="col-xs-10 col-sm-5" name="types">
<option value="">PLEASE CHOSE</option>
<option value="STATE">STATE</option>
<option value="FACULTY">FACULTY</option>
<option value="PROGRAME">PROGRAME</option>
</select>
<div id="showList"></div>
jQuery AJAX
<script type = "text/javascript" >
$(document).ready(function () {
$("select#form-types").change(function () {
var types = $("select#form-types").val();
if (types != null) {
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function (response) {
$("#showList").html(response);
}
}
});
});
});
</script>
Post Page (ajaxInfo.php)
<?php
if (isset($_POST["types"]) === TRUE){
$types = $_POST["types"];
}
else{
$types = null;
}
include '../dbco.php';
$query = $dbc -> query ("SELECT child FROM infobase WHERE parent='$types'");
if ($query -> num_rows > 0){
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc()){
echo "$count" . $result['child'] . "<br />";
count++;
}
}else{
echo "NO " . $types . " REGISTERED";
}
?>
Thank You.
You are using id (form-types) for your select input field. but your are tying to targeting another id (form-jenis).
use same named id for select input field and in your jquery selector.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(e){
e.preventDefault();
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'show.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
You have a missing bracket
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
}); // add this
</script>
I found out that my ajax jQuery function do not have close pair, so i decide to add it and it work.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}); // Add This
}
});
});
</script>
After the code running good, i also found out the error at ajaxInfo.php, the count inside the loop missing $ symbol
if ($query -> num_rows > 0)
{
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc())
{
echo "$count" . $result['child'] . "<br />";
$count++; //HERE
}
}
Thanks for the people that help.

Dynamically created select list makes mutilple calls to javascript function

I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.
HTML CODE:
<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];
if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->
<?php } ?>
</SELECT>
</td>
Javascipt code:
function get_type()
{
$(".channelname").live("change", function() {
var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
}
remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript
put this
<SELECT name="channel_name[]" required class='channelname'>
and javascript
$(".channelname").change(function() {
var channel_id = $('.channelname').find("option:selected").attr("value");
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});

Categories

Resources