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
}
?>
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.
I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}
This is my HTML Code
<input type="text" class="form-control" id="stfmail" name="staffmail" placeholder="E-Mail" required="required"><span id="result"></span>
In jQuery Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
PHP
if($_POST)
{
$username = $_POST['name'];
$ob->useravailable($username);
}
public function useravailable($username)
{
$stmt=$this->conn->prepare("select user_name from users where user_name=:uname and delet='0'");
$stmt->execute(array(':uname'=>$username));
if($stmt->rowCount()>0)
{
echo "<span style='color:brown;'>Sorry username already taken !!!</span>";
}
else
{
echo "<span style='color:green;'>available</span>";
}
}
Here i type a username..but in useravailable function only else part is working.. I type Existing username it works the else part available message is shown..
Please help me
thanks
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
if(data) {
$(".redbold").html('already this username is there ').show();
$("#username").focus();
}
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
if($_POST)
{
$username = $_POST['name'];
$query = mysql_query("SELECT user_name from users where user_name ='".$username ."' ", $con);
while ($row = mysql_fetch_assoc($query)) {
echo $row['user_name '];
}
}
I have drop down Select box as follows
<?php
$sql = "SELECT scheduleName FROM schedule";
$result = mysqli_query($link,$sql);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
?>
And I have a file called processClg.php as follows
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE 'Row id of drop down selection'";
$res = mysqli_query($link,$qry);
}
?>
How can I call processClg.php file on $("#schedule").change(function ());by assigning Row id of drop down selection as where condition.
Update
Am getting Response from processClg.Php as follows
[{"id":"2","scheduleName":"shanth","subject":"Patho","university":"Dali","facultyName":"Dr","scheduleStartDate":"2015-06-05","scheduleEndDate":"2015-06-09"}]
How to assign response values from ajax call to the following Php variables
<?php
$scheduleStartDate = '';
$scheduleEndDate = '';
?>
Any help my greatly appreciated.
$("#schedule").change(function() {
var value = $('#schedule option:selected').text();
var ajaxCheck = $.ajax({
url: 'processClg.php',
type: 'POST', // had mention post bcoz u mention in processClg.php
dataType: 'json', // processClg.php will return string means change to text
data: { id: value },
success: function(data){
console.log('success');
itrToRead(data);
}
});
});
function itrToRead(data) {
$(data).each(function(key, value){
console.log('key is: '+key+' and value is: '+value);
});
}
processClg.php
<?php
include "config.php";
if ($_POST['type']=='POST') {
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['id']."'";
$res = mysqli_query($link,$qry);
echo $res;
}
?>
You can call ajax as follows:
var RowId;
$.ajax({
type: "POST",
async: false,
url: url,
data: postdata,
//dataType: "json",
success: function (data) {
RowId = data;
}
});
The fact is that to assign response to variable is pass the parameter async: false,
Then its work.
I guess you have your dropdown in your rendered page and you want to send the selected value to the php page:
$("#schedule").change(function(){
var val2pass = $(this).find(':selected').val(); // get the value
$.ajax({
url: 'processClg.php',
type:'post', // <-----you need to use post as you are using $_POST[]
data: { rowid : val2pass }, //<---pass the value
success: function(data){
itrToRead(data);
}
});
});
So now on the php side you need to do this:
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['rowid']."'";
$res = mysqli_query($link,$qry);
}
?>
Your procellClg.php will be
<?php
include "config.php";
if (isset($_REQUEST['qid']))
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_REQUEST['qid']."'";
$result = mysqli_query($link,$qry);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
}
?>
and then make Ajax function call
$("#schedule").change(function() {
val = $(this).val();
$.ajax({
type: "POST",
async: false,
url: 'processClg.php',
data: {qid:val},
success: function(data){
$(this).html(data);
}
});
});
Im working om a menu system.
I use a query to get the menu list from the database.
On that table I also have an edit and delete option.
The edit and delete both works, but the edit function get activated on the TR.
I want to activate the edit function when I click on the edit TD.
When I just simply change
$(".edit_tr").click(function()
to
$(".editmenu").click(function()
It does the job, but it only changes the value in the input field, not in the html and or database.
Ill hope u guys know what I mean, and can help me out.
Thanks in advance.
Here's the code:
Javascript:
// delete menu
$(document).ready(function() {
// delete the entry once we have confirmed that it should be deleted
$('.delete').click(function() {
var parent = $(this).closest('tr');
$.ajax({
type: 'get',
url: 'deletemenu.php', // <- replace this with your url here
data: 'ajax=1&delete=' + $(this).attr('id'),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.fadeOut(300,function() {
parent.remove();
});
}
});
});
});
// edit menu
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#menunaam_"+ID).hide();
$("#voorgerecht_"+ID).hide();
$("#hoofdgerecht_"+ID).hide();
$("#nagerecht_"+ID).hide();
$("#prijs_"+ID).hide();
$("#menunaam_input_"+ID).show();
$("#voorgerecht_input_"+ID).show();
$("#hoofdgerecht_input_"+ID).show();
$("#nagerecht_input_"+ID).show();
$("#prijs_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var menunaam=$("#menunaam_input_"+ID).val();
var voorgerecht=$("#voorgerecht_input_"+ID).val();
var hoofdgerecht=$("#hoofdgerecht_input_"+ID).val();
var nagerecht=$("#nagerecht_input_"+ID).val();
var prijs=$("#prijs_input_"+ID).val();
var dataString = 'id='+ ID +'&menunaam='+menunaam+'&voorgerecht='+voorgerecht+'&hoofdgerecht='+hoofdgerecht+'&nagerecht='+nagerecht+'&prijs='+prijs;
$("#menunaam_"+ID).html('<img src="load.gif" />'); // Loading image
if(menunaam.length>0&& voorgerecht.length>0&& hoofdgerecht.length>0&& nagerecht.length>0&& prijs.length>0)
{
$.ajax({
type: "POST",
url: "editmenu.php",
data: dataString,
cache: false,
success: function(html)
{
$("#menunaam_"+ID).html(menunaam);
$("#voorgerecht_"+ID).html(voorgerecht);
$("#hoofdgerecht_"+ID).html(hoofdgerecht);
$("#nagerecht_"+ID).html(nagerecht);
$("#prijs_"+ID).html(prijs);
}
});
}
else
{
alert('Vul de velden in');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
And the PHP for the table's
$sql = "SELECT * FROM menus";
$result = mysql_query($sql);
echo "<table>";
echo "<th>#</th> <th>Menu naam</th> <th> Voorgerecht </th> <th> Hoofdgerecht </th> <th> Nagerecht </th> <th> Prijs </th> <th></th><th></th>";
while($row = mysql_fetch_assoc($result)) {
$menunr = $row['menunr'];
$menunaam = $row['menunaam'];
$voorgerecht = $row['voorgerecht'];
$hoofdgerecht = $row['hoofdgerecht'];
$nagerecht = $row['nagerecht'];
$prijs = $row['prijs'];
// open tr
echo "<tr id='$menunr' class='edit_tr'>";
echo "<td>$menunr</td>";
echo "<td><span id='menunaam_$menunr' class='text'>$menunaam</span><input type='text' value='$menunaam' class='editbox' id='menunaam_input_$menunr'/></td>";
echo "<td><span id='voorgerecht_$menunr' class='text'>$voorgerecht</span><input type='text' value='$voorgerecht' class='editbox' id='voorgerecht_input_$menunr'/></td>";
echo "<td><span id='hoofdgerecht_$menunr' class='text'>$hoofdgerecht</span><input type='text' value='$hoofdgerecht' class='editbox' id='hoofdgerecht_input_$menunr'/></td>";
echo "<td><span id='nagerecht_$menunr' class='text'>$nagerecht</span><input type='text' value='$nagerecht' class='editbox' id='nagerecht_input_$menunr'/></td>";
echo "<td><span id='prijs_$menunr' class='text'>$prijs</span><input type='text' value='$prijs' class='editbox' id='prijs_input_$menunr'/></td>";
echo "<td id='$menunr' class='editmenu'>edit</td>";
echo "<td><div class='delete' >delete</div></td>";
// close tr
echo "</tr>";
}
echo "</table>";
?>
And the ajax url php files
deletemenu.php
<?php
include 'config.php';
if(isset($_GET['delete']))
{
$query = 'DELETE FROM menus WHERE menunr = '.$_GET['delete'];
$result = mysql_query($query);
}
?>
editmenu.php
<?php
include("config.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$menunaam=mysql_escape_String($_POST['menunaam']);
$voorgerecht=mysql_escape_String($_POST['voorgerecht']);
$hoofdgerecht=mysql_escape_String($_POST['hoofdgerecht']);
$nagerecht=mysql_escape_String($_POST['nagerecht']);
$prijs=mysql_escape_String($_POST['prijs']);
$sql = "update menus set menunaam='$menunaam',voorgerecht='$voorgerecht',hoofdgerecht='$hoofdgerecht',nagerecht='$nagerecht',prijs='$prijs' where menunr='$id'";
mysql_query($sql);
}
?>