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";
}
}
My Answer:
It looks like you are trying to dynamically change the display of buttons based on the response from your AJAX call.
One thing to note is that you have spaces in your button IDs, which may cause issues when trying to select them in your JavaScript code. It's better to remove the spaces from the IDs.
Here is an updated version of your JavaScript code:
javascript
function enable(id) {
var id = id;
$.ajax({
type: 'POST',
url: "",
data: {'id': id},
cache: false,
dataType: "html",
async: false,
success: function(data){
$('#response').html(data);
if (jQuery.trim(data) == "disabled") {
$('#enable_' + id).hide();
$('#disable_' + id).show();
} else {
$('#disable_' + id).hide();
$('#enable_' + id).show();
}
}
});
}
And update your HTML buttons to remove spaces from the IDs:
html
status)==1) {?>
By using IDs without spaces and selecting them with jQuery, you should be able to dynamically change the display of the buttons based on the AJAX response.
Rate this post
4 of 5 based on 6826 votesComments