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>
Related
I am trying to make some code where a click of a SQL html button can display a different SQL table as a popup. I have already gotten the variable from the table to pass through using this:
echo "<td><a class='btn-floating btn-large waves-effect waves-light black' onclick='partSearch(".$product.")' value='display'><i class='material-icons'>search</i></a></td>";
The 'part search' code is as follows:
<script type="text/javascript">
function partSearch() {
$.ajax({
url: 'serv.php?id=<?php echo $product ?>',
type: 'GET',
success: function(result){
var obj = jQuery.parseJSON(result)
alert(obj)
}
})
}
</script>
Even though the variable is passed through to 'serv.php', I can't manage to get the sql data to be returned as a popup using alert. All I get is either nothing or [object, Object]. This is the SQL/php code:
<?php
include 'includes/dbh.inc.php';
$id = $_GET['id'];
$result = mysqli_query($conn,"SELECT * FROM pr WHERE product_ID='".$id."'");// test this
$rows = array();
while($r = mysqli_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
?>
Any help is appriciated
<script type="text/javascript">
function partSearch() {
var product_id = "<?php echo $product; ?>";
$.ajax({
url: 'serv.php?id=product_id',
type: 'GET',
success: function(result){
alert(result);
}
})
}
</script>
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>
So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";
I am using CKEditor version 4 and posting data from editor through ajax call however sometimes all the data post successfully and sometimes it just truncates it. As far I know the reason behind this is when editing the data it adds " " which cause this to truncate. Any help how to completely resolve this issue ?
My code
<script type="text/javascript">
var editor = CKEDITOR.replace('message');
function checkSubmit() {
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances['message'].updateElement();
}
var dataString = "action=<?php echo $_REQUEST['action']; ?>" +
"&id_user=<?php echo $_REQUEST['id_user']; ?>" +
"&sub_id=<?php echo $_REQUEST['subject_id']; ?>" +
"&subject_id=<?php echo $_REQUEST['actual_subject_id']; ?>" +
"&message="+ CKEDITOR.instances['message'].getData()+
"&subject_name="+$("#subject").text() +
"&occurence_name="+$("#occurency").text();
$.ajax({
type: "POST",
url: "data/user-student-data.php",
data: dataString,
success: function(data) {
// close window
parent.closeDistributeModal( 1, "<?php echo $_REQUEST['action']; ?>", <?php echo $_REQUEST['id_user']; ?>,<?php echo $_REQUEST['subject_id']; ?> );
}
});
}
</script>
That is a very difficult way to gather up the data. Try this instead:
var data = {};
data.subject_id = '<?php echo $_REQUEST['actual_subject_id']; ?>';
data.id_user = '<?php echo $_REQUEST['id_user']; ?>';
data.action = '<?php echo $_REQUEST['action']; ?>';
data.sub_id = '<?php echo $_REQUEST['subject_id']; ?>';
data.occurence_name = $("#occurency").text();
data.subject_name = $("#subject").text();
data.message = CKEDITOR.instances['message'].getData();
$.ajax({
type: "POST",
url: "data/user-student-data.php",
data: data,
success: function(returnedData) {
// whatever you had here
}
});
Also
// You can remove the for completely.. THIS:
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances['message'].updateElement();
}
// Is the same as this (you don't use the instanceName variable at all)
CKEDITOR.instances['message'].updateElement();
With reference to This link
, I am trying to delete rows dynamically from a table. Here's my Javascript function:
function deleteBox(id){
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_"+id).slideUp(1000);
}else{
// Just hide data
$("#list_"+id).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
}
}
However, calling it from Echo in Php, doesn't seem to invoke it. Here's my PHP code:
echo "<td align=\"center\">" . $id."</td>";
echo "<td><a href = 'javascript:deleteBox($id)'>Delete</a></td>";
Please correct me wherever I'm goin wrong. An early help would be highly appreciated.
<td><a href = 'javascript:deleteBox($id)'>Delete</a></td>
to
echo "<td><a onClick='deleteBox(" . $id . ");'>Delete</a></td>";
In my opinion, thats how I would do it..
Edited and shortened the jscript;
function deleteBox(idDelete){
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
$("#flash_" + idDelete).show();
$("#flash_" + idDelete).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.post('delete.php', {'id': idDelete}, function(result) {
if(result){
$("#flash_" + idDelete).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_" + idDelete).slideUp(1000);
}else{
// Just hide data
$("#list_" + idDelete).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
});
}
in your delete.php:
$_POST['id']
to retrieve the ID.
Check this, Hope this helps. Instead of id, static values are given
<td align="center">1</td>
<td><a href='#' onclick='deleteBox(1)'>Delete</a></td>
echo "<td><a href='#' onclick='deleteBox(1)'>Delete</a></td>";
jsfiddle
I am updating the answer, check whether alert is working.
<script>
function deleteBox(a){
alert(a);
}
</script>
<?php
echo "<a href='#' onclick='deleteBox(1)'>Delete</a>";
?>
Since you're using jQuery, I wouldn't do the call to the function in the href. Try something like this:
Javascript:
$(function() {
$('.delete').click(function() {
var id = $(this).attr('data-id');
alert ("Inside Method");
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(400).html('<img src="img/loading.gif" /> ');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
var randNum=Math.floor((Math.random()*100)+1);
if(randNum % 2==0){
// Delete with slide up effect
$("#list_"+id).slideUp(1000);
}else{
// Just hide data
$("#list_"+id).hide(500);
}
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
});
});
PHP/HTML:
echo "<td align=\"center\">" . $id."</td>";
echo "<td><a class='delete' data-id='" . $id . "'>Delete</a></td>";