Update sql database by clicking checkbox without submit button using ajax - php

I am searching for a way to update my sql database without refreshing the page by selecting the checkbox.
I am trying to achieve the id to be passed to the dolead.php when the user selects the checkbox and than check whether the id is higher than 0 it must pass the value 1 otherwise the value 0. Afther that check i need the database to be updated with the where clause the posted id. Below my code, what am i doing wrong? i get no errors in my logs and i have the error logging stated as followed: mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
PHP the user is seeing to select the switch box to trigger a select and the jquery to trigger the post.
<head>
<script src="jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="switch.css" type="text/css">
</head>
<body>
<table id="myTable" align='left' class="deftable">
<thead>
<tr>
<th style="width:10px !important;">!!</th>
<th>Name</th>
<th>Notes</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<? //Selecteer accounts.
$stmt = $mysqli->prepare("SELECT * FROM account WHERE purpose = 'Crew4' AND level <= ? AND betaald = 'yes'
AND group_name = ? AND secret = 'no' ");
$stmt->bind_param("is", $status,$groupname);
$stmt->execute();
$result = $stmt->get_result(); //only works when nd_mysli is set on the server!
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td class="footer">
<label class="switch">
<input type="checkbox" <?php if($row['do_lead']=='1') {
echo 'checked="checked"';
} ?> value="<?php echo filter_var($row['id'], FILTER_VALIDATE_INT); ?>" />
<div class="slider round">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
</label></td>
<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= htmlspecialchars($row['notes']) ?></td>
<td><?= htmlspecialchars($row['purpose']) ?></td>
</tr>
<? } ?>
</table>
</body>
<script>
$(document).ready(function()
{
var x=$("input[type=checkbox]").length;
$('input[type=checkbox]').on('change', function(i)
{
if($(this).is(':checked'))
{
x-=1;
if(x==0)
{
var val = [];
$(':checkbox:checked').each(function(i)
{
val[i] = $(this).val();
});
var jsonString = JSON.stringify(val);
$.ajax(
{
type: "POST",
url: "dolead.php",
data: {checkbox_value:jsonString},
cache: false,
success: function(data)
{
/* alert if post is success */
}
});
}
}
else
{
x+=1;
}
});
});
</script>
</html>
The dolead.php to retrieve the post value and update the database;
$data = json_decode(stripslashes($_POST['checkbox_value']));
foreach($data as $d){
if($d > 0){$leadupdate = 1;}
if($d == ''){$leadupdate = 0;}
$stmt48 = $mysqli->prepare("UPDATE account SET do_lead = ? WHERE id = ? ");
$stmt48->bind_param("ii", $leadupdate,$d);
$stmt48->execute();
$stmt48->close();
}
?>
PS: the connection file is included but not shown here..

You could add a class to the input and set the value dynamically:-
View:-
<input class="active" type="checkbox" value="$row['do_lead']" >
jQuery/AJAX Call:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$("input.active").click(function() {
// store the values from the form checkbox, then send via ajax below
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $(this).attr('value');
$.ajax({
type: "POST",
url: "dolead.php",
data: {id: check_id, active: check_active}
success: function(response){
alert('Data Updated Successfully');
}
});
return true;
});
});
</script>
PHP:-
// CLIENT INFORMATION
$active = mysqli_real_escape_string($_POST['active']);
$id = mysqli_real_escape_string($_POST['id']);
//update query.
//execute query.
Note:- for more info regarding click()
https://api.jquery.com/click

Related

Trying to update a table using contenteditable td and storing data using php into sql database

I'm echoing information from a database using a while loop in php and would then like to be able to directly edit the td and then press a button to save the changes to the database. I've looked online and found some code that uses JQuery and Ajax to do this but I can't seem to get it to work for me. I'm very new to coding so any help would be greatly appreciated on this!
I've tried a few different methods of doing this and this seemed the most straight forward way, I've tried to use an update query but am not familiar enough with the different languages to know if I've linked them all correctly.
This is the html - I've got all the db connections and everything in previously -
<div class="users_table">
<table>
<thead>
<tr>
<th>House ID</th>
<th>House Name</th>
<th>Motto</th>
</tr>
</thead>
<tbody>
<?php
$STH = $DBH->prepare("SELECT * FROM houses");
$STH->execute(array());
while ($row = $STH->fetch()) {
$house_id = $row->house_id;
$house_name = $row->house_name;
$house_motto = $row->house_motto;
$house_colour = $row->house_colour;
?>
<tr>
<form method="post" action="">
<td><?php echo $house_id; ?></td>
<section id="editable" contenteditable="true">
<td contenteditable><?php echo $house_name; ?></td>
<td contenteditable><?php echo $house_motto; ?></td>
</section>
<td><input type="button" id="save" value="Save Changes"></td>
<td> <input type="button" id="clear" value="Clear Change" /></td>
<input type="hidden" name="house_id" value="<?php echo $house_id; ?>">
</form>
</tr>
<?php } ?>
</tbody>
</table>
</div>
This is the JS file -
$(document).ready(function(){
// alert("Hello! I am an alert box!!");
$('.update_form').click(function() {
$('.slide_down').slideToggle('slow');
});
alert("Hello! I am an alert box!!");
var editable = document.getElementById('editable');
addEvent(editable, 'blur', function () {
// lame that we're hooking the blur event
localStorage.setItem('contenteditable', this.innerHTML);
document.designMode = 'off';
});
addEvent(editable, 'focus', function () {
document.designMode = 'on';
});
addEvent(document.getElementById('clear'), 'click', function () {
localStorage.clear();
window.location = window.location; // refresh
});
if (localStorage.getItem('contenteditable')) {
editable.innerHTML = localStorage.getItem('contenteditable');
}
$(document).ready(function(argument) {
$('#save').click(function(){
// Get edit field value
$edit = $('#editable');
$.ajax({
url: 'get.php',
type: 'post',
data: {data: $edit},
datatype: 'html',
success: function(rsp){
alert(rsp);
}
});
});
});
});
This is the get.php file -
//get.php
<?php
$editData = $_POST['data'];
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['data']))
{
// get variables from the URL/form
$house_id = $_POST['house_id'];
$house_name = htmlentities($_POST['house_name'], ENT_QUOTES);
$house_motto = htmlentities($_POST['house_motto'], ENT_QUOTES);
$house_colour = htmlentities($_POST['house_colour'], ENT_QUOTES);
// if everything is fine, update the record in the database
$STH = $DBH->prepare("UPDATE users SET house_name = ?, house_motto = ?, house_colour = ? WHERE house_id = ?");
$STH->execute(array($house_name,$house_motto,$house_colour,$house_id));
}
echo $editData;
?>
I know the jquery file is linked as the alert shows up but am not sure why it's not inserting the updated data into the db.

I want to show data in tables when ajax is called in php

I want to show only those data. which is selected in the dropdown list.
<select name="select" id="select">
<?php
$conn = mysqli_connect("localhost","root","","select");
$query = mysqli_query($conn,"select * from users");
while( $row = mysqli_fetch_array($query)){
?>
<option value="<?= $row['id'];?>"><?php echo $row['first_name'];?></option>
<?php } ?>
</select>
And then I want to only selected data from the dropdown in that table.
<table border="1">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Jobtitle</th>
<th>DOB</th>
</tr>
</thead>
<tbody id="data" >
</tbody>
</table>
This is the ajax code. but I don't know what can I write in the success: function() to show the data in tabular form.
<script>
$('#select').change(function(){
var LocateId = $('#select').val();
$.ajax({
url: 'getSelect1.php',
type: 'post',
data : {id: LocateId},
success:function(data)
{
}
});
});
</script>
And This is the getSelect1.php page. which fetch the data from the database and returns it JSON format.
<?php
$conn = mysqli_connect("localhost","root","","select");
$id = $_POST['id'];
$query = "select * from users where id = '$id'";
$cm = mysqli_query($conn,$query);
$data = array();
while( $rows = mysqli_fetch_assoc($cm) ) {
$data[] = $rows;
}
echo json_encode($data);
?>
You need to append html data like below:
<script>
$('#select').change(function() {
var LocateId = $('#select').val();
$.ajax({
url: 'getSelect1.php',
type: 'post',
data: {
id: LocateId
},
success: function(data) {
$("#data").html("");
$.each(data, function(k, v) {
if (v.state_id == $("state").val()) {
$("#data").append(`<tr>
<td>` + data.name + `</td>
<td>` + data.name + `</td>
<td>` + data.name + `</td>
<td>` + data.name + `</td>
</tr>`);
}
});
}
});
});
</script>
make sure you need to pass state_id column in you ajax response to match with state drop down id.
Please make sure before adding question on stack, you are clear on your question.

How to delete a row and display updated database without refreshing using ajax

I have a challenge with a project i'm working on and have tried all i could to get it working without success. Any assistance will be appreciated please.
I built an HTML/Bootstrap form whose fields value are sent to mysql database with ajax function and displays the updated database on the page without refreshing the page, the part which works fine.
Each row has a delete button. However, when I delete any of the displayed rows, only the first row I click gets deleted and the updated database displays. Subsequent attempts to delete any other row doesn’t work, until the page is reloaded and the process is repeated then only the first delete operation works again. My challenge is to get the delete button delete a row, fetch and display the updated database immediately without having to refresh the page.
Here is my ajax call:
var pry= $("#pry").val();
var sec = $("#sec").val();
var coll = $("#coll ").val();
var urlId = window.location.search.substring(1);
var pageId = urlId.split('=')[1];
//Insert into DB
$.ajax({
url: "process.php",
type: "POST",
async: false,
data:
{
"done": 1,
"pry": pry,
"sec": sec,
"coll": coll,
"page_id": pageId
},
success: function(){
displayFromDb();
clearInputs();
}
});
//delete from db
$(".my_butn").on("click", function(e){
e.preventDefault();
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "delete.php",
async: false,
data:
{
"pry": pry,
"sec": sec,
"coll": coll,
"page_id": pageId,
“id”: id
},
success: function(){
displayFromDb();
}
});
});
//function displayFromDb
function displayFromDb(){
$.ajax({
type: "POST",
url: "process.php",
async: false,
data:
{
"display": 1,
"page_id": pageId
},
success: function(d){
$("#tab-display").fadeIn().html(d);
}
});
}
//process.php file
<?php
//Insert to sql
if (isset($_POST["done"])){
$conn = mysqli_connect('localhost', 'root', '', 'educ');
$student_id = mysqli_real_escape_string($conn, $_POST['page_id']);
$pry = mysqli_real_escape_string($conn, $_POST["pry"]);
$sec = mysqli_real_escape_string($conn, $_POST["sec"]);
$coll = mysqli_real_escape_string($conn, $_POST["coll"]);
$sql = mysqli_query($conn, "INSERT INTO students (id, student _id, pry, sec, coll) VALUES (' ', '$student_id ', '$pry', '$sec', '$coll')");
}
//display from sql
if (isset($_POST['display'])){
$i=1;
$sql2 = mysqli_query($conn, "SELECT id, pry, sec, coll FROM students WHERE student_id = '$student_id");
if ($sql2){
echo '<table class="table table-striped table-bordered"><thead><tr><th>S/N</th><th>ID</th><th>PRY EDUC</th><th>SEC EDUC</th><th>COLL EDUC</th><th>DEL ROW</th></tr></thead>';
while ($row = mysqli_fetch_array($sql2, MYSQLI_ASSOC)){
$id = $row['id'];
$pry = $row['pry'];
$sec = $row['sec'];
$coll = $row['coll'];
$del = "<button type='button' class='btn btn-danger' id='$id'> X</button>";
echo '<tbody><tr><td>'.$i.'</td><td>'.$id.'</td><td>'.$pry.'</td><td>'.$sec.'</td><td>'.$coll.'</td><td>'.$del.'</td></tr></tbody>';
$i++;
}
echo '</table>';
}
}?>
And my delete.php file here
<?php
$conn = mysqli_connect('localhost', 'root', '', 'educ');
$student_id = mysqli_real_escape_string($conn, $_POST['page_id']);
$pry = mysqli_real_escape_string($conn, $_POST["pry"]);
$sec = mysqli_real_escape_string($conn, $_POST["sec"]);
$coll = mysqli_real_escape_string($conn, $_POST["coll"]);
$id = $_POST["id"];
$sql = mysqli_query($conn, "DELETE FROM students WHERE id = '$id' ");
}
?>
A simplistic approach....
Change 1:
In delete.php, you could add the following code after executing the DELETE query:
echo mysqli_affected_rows($conn);
die;
This means that the AJAX call would receive whatever is echoed value. Now, mysqli_affected_rows() would return 0 if no rows were deleted or -1 if there was an error, which can be checked in the success section of $.ajax() to relay the appropriate messages to the user.
Once you've checked that the number of deleted rows is > 0, the <tr> corresponding to the button can then be removed safely. Please check the following code snippet which might be of some help in achieving this. You'd just need to wrap this code inside success : function(delete_count){ .... }
Change 2:
$(".my-del-btn").on("click", function(){
// AJAX call, success: function(delete_count)
//if(delete_count > 0){
$(this).parents().closest("tr").fadeOut(1000)
.promise().done(function(){
$(this).parents().closest("tr").remove();
});
//}
//else{
// console.log("Error in deleting id = " + id);
//}
});
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.css"
rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css"
rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>DEL ROW</th>
</tr>
</thead>
<tbody>
<tr>
<td> 1 </td>
<td>
<button type='button' class='btn btn-danger my-del-btn'>DELETE</button>
</td>
</tr>
<tr>
<td> 2 </td>
<td>
<button type='button' class='btn btn-danger my-del-btn'>DELETE</button>
</td>
</tr>
<tr>
<td> 3 </td>
<td>
<button type='button' class='btn btn-danger my-del-btn'>DELETE</button>
</td>
</tr>
</table>
</body>
A few important notes:
As the post linked in the comments above would indicate, having async: false is, in a way, detrimental to the application (besides it being deprecated in jQuery 1.8 onwards).
Please take a look at and consider implementing MySQLi Prepared Statements to secure your PHP code from SQL Injection Attacks.

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

Fetching Data From Mysql With PHP, Ajax

I have database with fields branch, name, code_member, status etc.
I am trying to fetch Names in dropdown menu with branch by group mysql query. And Then Show Details Of NAME Selected In Dropdown List. But No Results are shown.
Selection Of Branch, Name And Auto Entering of Name In Search Box is working perfectly. But After That ID, Name, Branch,Code Number etc. data is not getting displayed.
There are three pages used. index.php, findName.php and searchfinal.php
Code I tried Is As Follows :
index.php :
<html>
<head>
<script type="text/javascript">
$(document).ready(function()
{
$(".branch").change(function()
{
var branch=$(this).val();
var dataString = 'branch='+ branch;
$.ajax
({
type: "POST",
url: "findName.php",
data: dataString,
cache: false,
success: function(html)
{
$(".getname").html(html);
}
});
});
});
</script>
<script>
$(document).ready(function()
{
$('#getname').change(function() {
$('#name').val($(this).val());
});
});
</script>
</head>
<body>
Branch :
<select name="branch" class="branch">
<option selected="selected">--Select Country--</option>
<?php
$sql=mysql_query("select branch from mutualbs group by branch");
while($row=mysql_fetch_array($sql))
{
$branch=$row['branch'];
echo '<option value="'.$branch.'">'.$branch.'</option>';
} ?>
</select> <br/><br/>
Name :
<select name="getname" id="getname" class="getname">
<option selected="selected">--Select Name--</option>
</select>
<br><br>
<hr>
<form method="get">
<label for="name">Name To Search :</label>
<input type="text" id="name" name="name" />
<button class="btnSearch">Search</button>
</form>
<br><br>
<table id="resultTable" style="color:#ff0000;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>MBS Number</th>
<th>Branch</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody> //** Results Are Not Getting Shown
</table>
<script src="../js/jquery-1.10.2.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script>
$jQuery(document).ready(function($) {
$('.btnSearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'searchfinal.php',
type: 'get',
data: {name: $('input#name').val()},
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
</body>
</html>
Till Search Button Everything working OK... But After Clicking Search Button, No Results i.e. ID, Name, Code Number, Branch And Status Shown..
Other Codes :
searchfinal.php
<?
require_once 'Connection.simple.php';
$conn = dbConnect();
if (isset($_GET['name'])) {
$data = "%".$_GET['name']."%";
$sql = "SELECT * FROM mutualbs WHERE name like ?";
$stmt = $conn->prepare($sql);
$results = $stmt->execute(array($data));
$rows = $stmt->fetchAll();
}
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['code_number']."</td>";
echo "<td>".$row['branch']."</td>";
echo "<td>".$row['status']."</td>";
echo "</tr>";
}
}
?>
Need Help....

Categories