i will like to change the status of a user in my database from inactive to active by clicking on a button.
i have a function already which show if the use is active or inactive on the database by asigning a value to them eg 0 for inactive and 1 for active.
below is the function that change the value on the button if the user is inactive or active
if ( $row["active"] == 1 ) {
echo '<button class="btn-u btn-u-green" type="button">Active</button>';
} else {
echo '<button class="btn-u btn-u-red" type="button">Inactive</button>';
}
now i need to create a function that handle the active and inactive button. like when an admin clicks on inactive (Button) it update the value into the database to 1 (Active), and if the admin click on the active button again it update the value to 0 (inactive),
below is what i have done so far
Button Table bellow
<td>
<?php
if ( $row["active"] == 1 ) {
echo '<button onclick="button" name="active" class="btn-u btn-green" type="button">Active</button>';
} else {
echo '<button name="inactive" class="btn-u btn-u-red" type="button">Inactive</button>';
}
?></td>
database settings
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "testone";
try
{
$conn = new PDO ("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["active"]))
}
$query = "INSERT INTO users(active) VALUE (:1)";
$statement = $conn->prepare($query);
$statement->execute(
array(
'users' => $_POST['active']
)
);
$count = $statement->rowCount();
if($count > 0)
{
echo "data insert successfully";
}
else
{
echo "data insertion failed";
}
}
}
catch(PODExeption $error)
{
echo $error->GetMessage();
}
?>
function i used
<script
src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous">
</script>
<script>
$(document).raedy(function(){
$('button[type="button"]').click(function(){
var active = $(this).val();
$.ajax({
url:"activateagent.php",
method:"POST",
data:{users:active},
success: function(data){
$('$result').html(data);
}
});
});
});
</script>
in my console i get this error ReferenceError: button is not defined
Thanks
There are so many errors in the code, make following changes:
<td>
<?php
if ( $row["active"] == 1 ) {
echo '<button class="btn-u btn-green btn_send" id="<?php echo $row["active"];?>">Active</button>';
} else {
echo '<button class="btn-u btn-u-red btn_send" id="<?php echo $row["active"];?>">Inactive</button>';
}
?></td>
Now in JQuery code make these changes:
$(document).ready(function(){
$('.btn_send').on('click',function(){
var active = $(this).attr('id');
$.ajax({
url:"activateagent.php",
method:"POST",
data:{users:active},
success: function(data){
$('$result').html(data);
}
});
});
});
Related
What I'm trying to achieve is a user to follow another user without having to refresh the page. So far I've played around and had no problem inserting and deleting the rows in mysql table, but now when I'm trying with AJAX I can't get it to work.
jquery
$(document).ready(function(){
$("#followbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#followbutton').hide();
$('#unfollowbutton').show();
// $("#unfollowbutton").hover(function(){
// $(this).text("Unfollow");
// }, function(){
// $(this).text("Unfollow");
// });
}
});
});
});
$(document).ready(function(){
$("#unfollowbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitUnfollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#unfollowbutton').hide();
$('#followbutton').show();
//I want the button to change its text to Following and when hovering it should say unfollow if user is followed
}
});
});
});
followuser.inc.php
<?php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if (isset($_POST["submitFollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('INSERT INTO userfollow (thefollower, theuserid, followstatus) VALUES (?,?,?)');
$followstatus = 1;
$stmt->bind_param('sss', $userthatisfollowed, $theuserid, $followstatus);
$stmt->execute();
echo $response = "<span>Followed!</span>";
$stmt->close();
} else if(isset($_POST["submitUnfollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('DELETE userfollow FROM userfollow WHERE thefollower = ? AND theuserid = ?');
$stmt->bind_param('ss', $userthatisfollowed, $theuserid);
$stmt->execute();
echo $response = "<span>Unfollowed!</span>";
$stmt->close();
} else {
echo "DID NOT WORK";
}
profile.php
if(isset($_SESSION["userid"]) && $_SESSION["userid"] != $userthatisfollowed) {
?>
<form action="<?php echo htmlspecialchars("includes/followuser.inc.php");?>" id="followform" method="post">
<?php
if ($resulted->num_rows > 0){
$subscribe_status = "Unfollow";
$subscribe_text = "Following";
} else {
$subscribe_status = "Follow";
$subscribe_text = "Follow";
}
echo "<button name='submit".$subscribe_status."' id ='unfollowbutton' type='submit' style='display:none'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
echo "<button name='submit".$subscribe_status."' id ='followbutton' type='submit'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
// echo "<button name='submit".$subscribe_status."' id ='notificationbell' type='submit' style='display:none'>";
// echo "<i class='fa fa-bell'></i>";
// echo "</button>";
echo "<div id='followmessage'></div>";
?>
<input type="hidden" name="theuserid" id="theuserid" value="<?php echo $_SESSION["userid"] ?>">
<input type="hidden" name="thefollower" id="thefollower" value="<?php echo $userthatisfollowed; ?>">
</form>
<?php
}
What's worth noting is that I'm getting the response DID NOT WORK which tells me that if(isset($_POST["submitUnfollow"])) is not set. However, If I try with if(isset($_POST["theuserid"]) && (isset($_POST["thefollower"])) then it actually works for the insert query but not for the delete query.
You're missing the submitFollow parameter in the data: object. Instead, you have followbutton: true, which isn't used by the PHP code. So change that to:
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFolow': 'true'},
And for the unfollow button, use submitUnfollow instead.
This is my first time using ajax with php . I have a register form where I check if the entered username already exists in a mongodb database . If it does then I show an error in my page , else I want to redirect to my index.php and start a session .
EDIT : I changed my script completely now I redirect succesfully .
The angularJS warning is gone !
register.php where I send my data for validation UPDATED!
$("#registerForm").submit((e)=>{
e.preventDefault();
var uname = $("#username").val();
var fname = $("#firstname").val();
var lname = $("#lastname").val();
var addr = $("#address").val();
var pw = $("#password").val();
var sub = $("#submitRegister").val();
var errorSubmit = $("#checkSubmitError").val();
$.ajax({
type:'POST',
data:{username:uname,firstname:fname,
lastname:lname,address:addr, password:pw ,
submitRegister:sub , checkSubmitError: errorSubmit },
url:'insertUser.php',
success:(data)=>{
if(data == 'success'){
window.location.href = '../php/index.php';
}else if(data =='failed'){
$("#username").val(""); //empty username field
var submitErr = $("#checkSubmitError");
var isHidden =submitErr.hasClass("hide");
if(isHidden){
submitErr.removeClass("hide");
submitErr.addClass("show");
}else{
submitErr.removeClass("hide");
submitErr.addClass("show");
}
}
},
error: (xhr)=>{
alert("error");
},
});
});
<body>
<form action = "insertUser.php" method= "POST" id ="registerForm" name= "regForm">
...my inputs with ids
<!-- button that submits form -->
<button type="submit" class="btn btn-success" id = "submitRegister" name="submit"
>Submit
</button>
<!--hidden error I display if username exists -->
<span id ="checkSubmitError" class= "hide text-danger"> </span>
</form>
</body>
Then in my insertUser.php where I check if username exists in my db UPDATED!
<?php
require '../vendor/autoload.php';
if(isset($_POST['submitRegister'])){
$m = new MongoDB\Client("mongodb://127.0.0.1/");
$db = $m ->ECommerce;
$collection = $db->users;
//check if username already exists
$alreadyExists = false;
$check = $collection->find(array('userName'=>$_POST['username']));
$count=0;
if(is_array($check) || is_object($check)){
foreach($check as $i){
$count= $count+1;
}
}
if($count==0){
$document = array(
"firstName" => $_POST['firstname'],
"lastName" => $_POST['lastname'],
"address" => $_POST['address'],
"userName" => $_POST['username'],
"password" => password_hash($_POST['password'] ,PASSWORD_DEFAULT)
);
$collection->insertOne($document); //inserts succesfully
$response = "success";
echo $response;
exit();
}else{
$alreadyExists = true;
$response = "failed";
echo $response;
exit();
}
}
?>
The code I edited in my example now works perfectly . It is over .
What I learned :
$ajax is better than $load method for redirecting .
To return data to success() function you echo $data in the php script then exit() .
These were the keypoints here .
I have this code and I want to add checkbox according to fetched number from database with PHP and when clicked on checkbox update a field in db with JQuery, this work for 1 checkbox but this cant work for more checkbox and Also my PHP loop does not work how i can add checkbox with loops and when user click on any checkbox update His own field on database, anybody can resolve my problem ?
My JQuery code:
$(document).ready(function () {
$('#mycheckbox').change(function () {
var returnVal = ("Are " + "you sure?");
if (returnVal) {
postToServer($(this).prop("checked"));
} else {
$(this).prop("checked", !$(this).is(":checked"));
}
});
function postToServer(state) {
let value = (state) ? 1 : 0;
$.ajax({
type: 'POST',
url: 'checkbox.php',
data: {'value': +value},
success: function (response) {
//handle response
}
});
}
}
and my PHP code:
$sql1="SELECT * FROM `users` ";
$result1= mysqli_query($conn,$sql1);
$row1=mysqli_fetch_assoc($result1);
$lights=$row1["lights"];
for ($i=0; $i < $lights; $i++){
if ($row["value"]=='1'){
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" checked=\"checked\">";
} else {
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" >";
}
}
This should fix the issue with your loop not running and should print out the checkbox for each user
$users= mysqli_query($conn, "SELECT * FROM user");
while($row = mysqli_fetch_assoc($users)) {
if ($row["value"]=='1'){
echo '<input type="checkbox" class="checkbox" id="mycheckbox-'.$row["id"].'" checked="checked">';
}else {
echo '<input type="checkbox" class="checkbox" id="mycheckbox-'.$row["id"].'" >';
}
}
Added the id of the user to each checkbox id in order to make each one have a unique id
$(document).ready(function () {
$('.checkbox').change(function () {
var returnVal = confirm("Are you sure?");
if (returnVal == true) {
postToServer($(this).val());
} else {
$(this).prop("checked", !$(this).is(":checked"));
}
});
function postToServer(state) {
let value = state;
$.ajax({
type: 'POST',
url: 'checkbox.php',
data: {'value': value},
success: function (response) {
//handle response
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
PHP Code :
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
?>
<input type="checkbox" class="checkbox" value="<?php echo $row["id"] ?>">
<?php
}
?>
I want to edit status field for selected column onclick of bootstrap checkbox toggle.....Please Help
Example :
1. if status is active then when user click then it should be update in database as inactive and reload page.
2. if status is inactive then when user click then it should be update in database as active and reload page.
Fetch Database
<?php
require_once 'db_config.php';
$output = array('data' => array());
// do not fetch status 3 because it is deleted
$sql = "SELECT *,emailnotificationstable.id as sid FROM notificationslist";
$query = $connect->query($sql);
$num_rows = mysqli_num_rows($query);
$x = $num_rows;
while ($row = $query->fetch_assoc()) {
// activate button
$activateButton = '';
if ($row['status'] == 1) {
$activateButton =
'<input type="checkbox" id="toggleBtn" name="toggleBtn" checked data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
} elseif ($row['status'] == 2) {
$activateButton =
'<input type="checkbox" id="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
}
// extra code here
$output['data'][] = array(
$x,
$activateButton,
$row['date'],
$row['notificationname'],
$row['employeename'],
$createdby,
$editedby,
$editeddate,
$deleteButton,
);
$x--;
}
// database connection close
$connect->close();
echo json_encode($output);
Jquery
// global the manage memeber table
var mytable;
$(document).ready(function() {
mytable = $("#mytable").DataTable({
"ajax": "../pages/php_action/salesexe/retriveemailnotifications.php",
"order": [],
"fnDrawCallback": function() {
jQuery('#mytable #adBtn').bootstrapToggle();
}
});
});
function editMember(sid = null) {
if(sid) {
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".edit-messages").html("");
// remove the id
$("#membersid").remove();
// click on toggle button
$("#adBtn").click(function() {
$.ajax({
url: 'notifstatus.php',
type: 'post',
data: {membersid : sid},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
mytable.ajax.reload(null, false);
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
}
}
});
}); // click toggle btn
} else {
alert('Error: Refresh the page again');
}
}
Update
<?php
require_once 'db_config.php';
$output = array('success' => false, 'messages' => array());
$membersId = $_POST['membersid'];
// update record to inactive
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = $membersId";
$query = $connect->query($sql);
if($query === TRUE) {
$output['success'] = true;
$output['messages'] = 'Notification trigger successfullt activated for selected user';
} else {
$output['success'] = false;
$output['messages'] = 'Error while activating notification trigger for selected user,';
}
// close database connection
$connect->close();
echo json_encode($output);
You're thinking way to complex with reloading a page, not using the API as you should. You only want to fetch the status and update the needed parts this means you need a proper way to identify a row in your table. Also an html id must be unique in a page better remove that.
You have a couple of options:
use datatables ajax requests so it can handle multiple edits on different cols.
toggle the button on and off using jquery and bootstrap.
Shown below is the latter:
$(function() {
// hooking event only on buttons, can do tr's as well.
$('.toggleBtn').click(function(){
$.ajax({
url: 'notifstatus.php',
type: 'post',
data: {
id : $(this).val(),
status: $(this).prop('checked')
},
dataType: 'json',
success: function(response){
if(response.success){
$(this).bootstrapToggle('enable');
console.log(response.message);
} else {
$(this).bootstrapToggle('disable');
BootstrapDialog.show({
title: 'failed to update status',
message: response.status + response.messages
});
}
},
error: function(xhr, textStatus, errorThrown) {
BootstrapDialog.show({
title: textStatus,
message: errorThrown
});
}
});
});
});
Now the only response to build is the following:
<?php
require_once 'db_config.php';
if(isset($_POST['status']) && $_POST['status']){
// user requests to turn off
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = ?"; // SQL injection, use prepared statements. fix it.
} else {
// user requests to turn on, other query.
}
$success;
$status = 0;
$message = 'Error while activating notification trigger for selected user,';
if($query = $connect->query($sql)){
if($row = $query->fetch_assoc()){
$success = true;
$message = 'Notification trigger successfully activated for selected user';
$status = $row['status'];
}
}
die(json_encode([
'success' => $success,
'messages' => $message,
'status' => $status
]));
?>
Should do the trick, no need to request all data to update a single value.
I have a list of 4 images of an item.
One of them should show up in another page as a link from that page to the item page.
I want to be able to check a box so that this one will be the main pic and will show up in the category page.
this is the code of the form:
$all_pics_of_item = fetch_all_pics_of_item($item_id);
//print_r($all_pics_of_item);
if(is_array($all_pics_of_item))
{
echo '<ul>';
foreach($all_pics_of_item as $key=>$val)
{
if ($val['pics_main']=='yes')
{
$set_checked = "checked";
$action = true;
}
else
{
$set_checked = "";
$action = false;
}
echo '<li style="float: left;margin:10px;border: 1px solid #000;padding:10px;">';
echo '<img style="width:120px;height:120px;" src="../../gallery_images/thumbs/'.$val['pics_source'].'">';
echo '<br>'.$val['pics_name'];
echo '<br><div class="delet"><b>x</b></div>';
echo '<br><form method="post" action="update_main_pic.php" enctype="text/plain" >
Show in cat. page<input type="checkbox" class="myCheckbox" name="main" value="no"'.$set_checked.'&action='.$action.' data-picid="'.$val['pics_id'].'" data-itemid="'.$item_id.'" />
</form>';
echo '</li>';
}
echo '<ul>';
}
Here is the AJAX and script:
$(document).ready(function(){
$(':checkbox').click(function() {
$(':checkbox').not(this).removeAttr('checked');
var picid = $(this).attr('data-picid');
var itemid = $(this).attr('data-itemid');
var action = $(this).is(':checked');
//if((this).attr('checked',true))
//{
// var action = true;
//}
//else
// {
// var action = false;
// }
$.ajax({
url: "ajax_update_main_pic.php",
type: "POST",
data: "itemid=" + itemid + "&picid=" + picid + "&action=" + action,
timeout:5000,
dataType: "html",
beforeSend:function(){
},
error: function(){
alert('Problem !');
},
success: function(msg){
if(msg == 'no')
{
}
else
{
}
},
complete: function(){
}
})
});
}); //END READY
Here is the update function:
<?php
require_once "../../db.php";
require_once "../../functions.php";
if(isset($_POST['itemid']) && isset($_POST['picid']) && isset($_POST['action']))
{
$item_id = $_POST['itemid'];
$pic_id = $_POST['picid'];
$action = $_POST['action'];
}
else
{
header('location: upload_image.php');
die();
}
if($action == 'true')
{
$pic_show = 'yes';
}
else
{
$pic_show = 'no';
}
//print_r($pic_show);
function update_main_pic($item_id, $pic_id, $pic_show )
{
global $db;
try
{
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pics_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_items_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_main', $pic_show, PDO::PARAM_STR);
$stmt->execute();
return true;
}
catch(Exception $e)
{
return false;
}
}
$result = update_main_pic($item_id, $pic_id, $pic_show );
if($result == false)
{
die('Problem updating pics');
}
else
{
header('location: upload_image.php?iid='.$item_id);
die();
}
?>
I always get 'Problem updating pics'
It looks like only the checked checkbox is transmitted, while I want that the column PIC_MAIN will show "yes" if this is the one chosen and "no" foe all other pics
The issue lies with your binding.
You sql has the following name variables :pic_show , :pic_id and :item_id but you are binding :pics_main', :pics_items_id and :pics_id.
Change your binding to:
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pic_show', $pic_show, PDO::PARAM_STR);