Select and Delete multiple rows by selecting checkboxes using PHP - php

Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
<input class='file' type="checkbox" class="form-control" name="hid" id="<?php $rs["carimgid"]; ?>" placeholder="Please choose your image">
this my ajax script where using this to delete multiple row without refresh
<script type="text/javascript">
$(document).ready(function(){
jQuery('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
jQuery('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
//alert(allVals.length); return false;
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
//$("#loading").show();
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
//for server side
var join_selected_values = allVals.join(",");
$.ajax({
type: "POST",
url: "delete.php",
cache:false,
data: 'ids='+join_selected_values,
success: function(response)
{
$("#loading").hide();
$("#msgdiv").html(response);
//referesh table
}
});
//for client side
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
jQuery('.remove-row').on('click', function(e) {
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
$('table tr').filter("[data-row-id='" + $(this).attr('data-id') + "']").remove();
}
});
});
</script>
and my php code is
<?php
include("config.php");
if(isset($_POST['ids'])){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid ='$id'");
}
?>
Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script

You haven't got the ids from POST.
Look at the following
$ids = mysqli_real_escape_string($con, $_POST['ids']);
if(!empty($ids)){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid IN ({$ids})");
}

Related

Load more button not working and showing all the records on the page

I have a page and I am displaying the list(MAX 200 records) on my page using ajax.
I am using the below code to call the ajax and show the response on the page.
And the second script is for a button called "Load More". I have to show the 20 records on the page then the user clicks on load more than displays the next 20 records.
Now, My issue is, I am getting all the records and load more button
$(document).ready(function(){
$.ajax({
url: 'function21.php',
method:'post',
dataType: "json",
data:{action:"employeelist21"},
success: function(data){
$('#employeelist').append(data);
}
})
});
$(document).ready(function(){
var list = $("#employeelist21 li");
var numToShow = 20;
var button = $("#next");
var numInList = list.length;
//alert(numInList);
list.hide();
if (numInList > numToShow) {
button.show();
}
list.slice(0, numToShow).show();
button.click(function(){
var showing = list.filter(":visible").length;
list.slice(showing - 1, showing + numToShow).fadeIn();
var nowShowing = list.filter(":visible").length;
if (nowShowing >= numInList) {
button.hide();
}
});
});
PHP
function employeelist21($pdo)
{
$query=" sql query here";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
$data='';
$data='<ul><li>
<div class="box">
<div><span>Company</span></div>
<div><span>Industry</span></div>
<div><span>Name</span></div>
<div><span>Location</span></div>
</div>
</li>';
foreach($results as $key){
$data.='<li>
<div class="box">
<div><h4>'.$key['Industry'].'</h4></div>
<div><p>'.$key['industry_name'].'</p></div>
<div><p>'.$key['name'].'</p></div>
<div><p>'.$key['city'].'</p></div>
</div>
</li>';
}
$data.='</ul><div class="text-center">Load More</div>';
}
else{
$data.='No records available';
}
echo json_encode($data);
}
First, I would rather transfer back a list of data (not html) in json format and use that like an array, creating the HTML for it in javascript. BUT we don't always get what we want, so in this case I would assign an attribute to each set of 20 like this:
// at the top of your script (not in a function)
let perPage = 20, onGroup=0
// in your ajax function ...
success: function(data){
$('#employeelist').hide();
$('#employeelist').append(data);
$('#employeelist box').each( function(index) {
if (index===0) return; //header row
$(this).data('group',Math.floor(index-1/perPage))
});
$('#employeelist box').hide()
$('#employeelist box [data-group=0]').show()
$('#employeelist').show();
}
Then for the button, remove this from the PHP and make it an element under the results div
<div class="text-center">Load More</div>
Then in your script
$(document).ready(function() {
$("#next").click(function(){
$('#employeelist box [data-group='+onGroup+']').hide()
onGroup++;
$('#employeelist box [data-group='+onGroup+']').show()
if ($('#employeelist box [data-group='+(onGroup+1)+']').length ===0) {
$(this).hide();
}
});
});
Hard to test here, but let me know if it doesn't work

How can I add a confirmation to a delete action made through Jquery?

I have a function in JQuery that combined with PHP and SQL deletes rows from a table, deleting them from the database.
When I click on the delete button, the rows are instantly deleted, however, I'd like to add another level of confirmation that asks if you really want to delete it.
Section that deletes the rows by referring the function
$userObj = mysqli_query($conn , 'SELECT * FROM `shifts`');
if(isset($_POST['data'])){
$dataArr = $_POST['data'] ;
foreach($dataArr as $id){
mysqli_query($conn , "DELETE FROM shifts where id='$id'");
}
echo 'record deleted successfully';
}
JQuery function
<script>
$(document).ready(function(){
$('#checkAll').click(function(){
if(this.checked){
$('.checkbox').each(function(){
this.checked = true;
});
}else{
$('.checkbox').each(function(){
this.checked = false;
});
}
});
$('#delete').click(function(){
var dataArr = new Array();
if($('input:checkbox:checked').length > 0){
$('input:checkbox:checked').each(function(){
dataArr.push($(this).attr('id'));
$(this).closest('tr').remove();
});
sendResponse(dataArr)
}else{
alert('No record selected ');
}
});
function sendResponse(dataArr){
$.ajax({
type : 'post',
url : 'includes/dbh.inc.php',
data : {'data' : dataArr},
success : function(response){
alert(response);
},
error : function(errResponse){
alert(errResponse);
}
});
}
});
</script>
Javascript has the confirm function that will return a boolean based on the user's selection of yes or no. You can use this to make the user confirm they want to delete the records inside of your click function.
$('#delete').click(function(){
if (confirm("Are you sure you want to delete this?")) {
var dataArr = new Array();
if($('input:checkbox:checked').length > 0){
$('input:checkbox:checked').each(function(){
dataArr.push($(this).attr('id'));
$(this).closest('tr').remove();
});
sendResponse(dataArr)
}else{
alert('No record selected ');
}
}
});

Using Ajax to store checkbox in database

Update: The code is working. I had an incorrectly named table in my php file.
I have the following that I've found from some snippets during my searches for help however I cannot get it to work. What I am trying to accomplish is clicking a check box and it automatically populate a row in my database that I can refer to on any other page. Right now when I click the checkbox, nothing happens.
HTML
<td><input type="checkbox" name="<?php echo $brow['WorkOrder']; ?>" value="<?php echo $brow['WorkOrder']; ?>"></td>
Ajax
<!-- Checkbox storage -->
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('functions/checkBox.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
});
</script>
functions/checkBox.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
include("../../db.php");
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO TemporaryCheckBoxID (WorkOrder) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
To check whether checkbox is checked or not use as below and try
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).is(":checked");
if(checked){
var value = $(this).val();
$.post('functions/checkBox.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
});

echo data into drop list using AJAX

I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag

Jquery Select list items in loop using keyup and key down

I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});

Categories