How to delete multiple records using php and ajax - php

I have multiple rows of news when I show them using php. I'm trying to remove multiple rows simultaneously using checkboxes next to each row.
This is my php code
<?
$select_news = $mysqli->query("SELECT * FROM news order by time desc limit $x,$numbershownews");
while ($rows_news = $select_news->fetch_array(MYSQL_ASSOC)){
$id_news = $rows_news ['id'];
$title_news = $rows_news ['title'];
?>
<table>
<tr rel="<? echo $id_news; ?>">
<td class="tdtable" id="<? echo $id_news; ?>" width="4%">
<input type="checkbox" rel="<? echo $id_news; ?>" name="checkbox[]" class="checkboxtable" value="<? echo $id_news; ?>">
</td>
<td class="tdtable" id="<? echo $id_news; ?>" width="50%">
<? echo $title_news; ?>
</td>
</tr
</table
<?
}
?>
<button class="deletecheckednews">Delete</button>
and this is jquery code
$(".deletecheckednews").on( 'click', function () {
var arr = new Array();
$(".checkboxtable:checked").each(function () {
arr.push($(this).attr("rel"));
});
if(arr == "") {
alertify.error("no selected news");
} else {
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: arr ,
cache: false,
success: function(data) {
alertify.success(data);
$.each(arr, function(key, value) {
$("tr[rel="+value+"]").fadeOut();
});
}
});
}
return false
});
How can I pass this array on to "delete_multiple_news.php"? I have tried this $checkedneww = $_REQUEST['arr']; and this $checkedneww = $_POST['arr']; but it doesn't work. How would I go about removing the selected rows?

On
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: {"array_del": arr} , / <-
cache: false,
success: function(data){
alertify.success(data);
In PHP use
$array_del = filter_input(INPUT_POST, 'array_del', FILTER_SANITIZE_STRING);
If you wanna see the result, just do:
In PHP ajax:
$array_del = filter_input(INPUT_POST, 'array_del', FILTER_SANITIZE_STRING);
echo json_encode($array_del);
In js:
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: arr ,
cache: false,
success: function(data){
alertify.success(data);
console.debug(data);
//$.each(arr, function(key, value) {
// $("tr[rel="+value+"]").fadeOut();
//});
}
});
To delete you can use WHERE in sql to filter the results who you want delete example. If the results are more than one, you make a loop or a commun column.
$mysqli->query(DELETE FROM table_name WHERE some_column = $array_del[some_column]);

You're passing a raw array in your ajax call (data: arr) but you're expecting a named variable ($_POST['arr']).
I'm not sure if data: arr is possible with jquery (haven't used it in years) but if it is, then the ids array you're looking for is simply $_POST in its whole.
If that's not the case, or you want to do $_POST['arr'] you should change your JS to data: {arr: arr}.

Related

can i fetch and populate different fields using function(data) jquery?

i want to populate two fields when some one fill up card no.
<input type="text" id="name" name="name" class="form-control" Value="<?php echo $grow['name']; ?>">
<input type="text" id="address" name="address" class="form-control" Value="<?php echo $grow['address']; ?>">
but this code populate field one by one. can any one suggest be better code for populating two fields from database. Thank you
jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k=$(this).val();
var q="name";
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q='+q,
cache: false,
success: function(data)
{
if(data){
$("#name").val(data);
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
$("#address").val(data);
}
}
});
}else
$("#name").val("");
$("#address").val("");
}
});
});
});
</script>
getresult.php
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select * from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
echo $row[$q];
?>
Try to extract both name and address from database and json them
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select address,name from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
$result = array(
'name'=>$row['name'],
'address'=>$row['address']);
echo json_encode($result);
After that parse them via jquery
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
var parsedData = jQuery.parseJSON(data);
$("#name").val(parsedData.name);
$("#address").val(parsedData.address);
}
}
});
Javascript Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k = $(this).val();
var q = "name";
$.ajax({
type: 'POST',
url: "getresult.php",
data: 'k='+k,
cache: false,
success: function(data)
{
var jsonArr = $.parseJSON(data);
if(typeof response =='object')
{
$("#name").val(jsonArr.name);
$("#address").val(jsonArr.address);
}
else
{
$("#name").val("");
$("#address").val("");
}
}
});
});
});
</script>
PHP Code:
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k = $_POST['k'];
$sql = mysql_query("select * from inward where krishi='$k'");
$row = mysql_fetch_assoc($sql);
echo json_encode(array('name' => $row['name'], 'address' => $row['address']);
?>

Pass checkbox values into an array using ajax to php

I am needing some help passing checkbox values into an array using ajax and retrieving the values in my controller. The following code is not working. I receive the error: "Invalid argument supplied for foreach()". Var_dump gives string(42) "Educator_Classes[]=1&Educator_Classes;[]=3
Thanks for any help you can provide.
My html form input:
<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>
My jquery:
$("#Send_Invite").click(function() {
var form_data = {
Opportunity_Id: $('#Opportunity_Id').val(),
Educator_Id: $('#Educator_Id').val(),
Educator_Classes: $('#Educator_Classes:checked').serialize(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('schedule/update_educator_class'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#response').html(data);
}
});
return false;
})
My controller:
function update_educator_class() {
$Educator_Id = $this->input->post('Educator_Id');
$Opportunity_Id = $this->input->post('Opportunity_Id');
$Educator_Classes = $this->input->post('Educator_Classes');
foreach($Educator_Classes as $Educator_Class):
$this->ion_auth_model->update_educator_class($Opportunity_Id, $Educator_Class, $Educator_Id);
endforeach;
}
You have to use [] for name attribute and not for id, otherwise it can't act like an array
<input type="checkbox" id="Educator_Classes" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>
And also your jQuery code can be simpler:
$("#Send_Invite").click(function() {
var form_data = $(this).closest('form).serialize();
form_data['ajax'] = 1;
$.ajax({
url: "<?php echo site_url('schedule/update_educator_class'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#response').html(data);
}
});
return false;
});
To debut what's passed to $Educator_Classes you can do this:
var_export($Educator_Classes);
The Solution is that you have to take the array of name attribute of checkbox.
Like :
<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>

Calling PHP file on button click

I have two different buttons in my page. clicking on the first one must call a php file named derive_rules.php while cliking on the second one must call another file named derive_rules1.php using ajax. For same i tried following code. But it is not working,
<script>
$(document).ready(function() {
$(".deriver").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules.php',
data: 'kw='+val+'&agent='+agent,
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
if(data.success == 'true') {
$("#results_holder").show();
$("#results").html(data.msg);
$("#keyword").val('');
}
else {
alert(data.msg);
}
}
});
}
});
});
</script>
and those are mu buttons
<td><b>+ New Rule</b></td>
<td><input type = "text" name = "Keyword" id = "keyword" style = "width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type = "button" value = "Verify" class = "Buttons deriver" rel = "<?php echo $_GET['id']; ?>"/></td>
<td><input type = "button" value = "Add" class = "Buttons deriver" rel = "<?php echo $_GET['id']; ?>"/></td>
</tr></table>
what changes should i apply on my code to make it work???? as i want
Here is the quick solution.
HTML
<button class="same" data="derive_rules">Button One</button>
<br/>
<button class="same" data="derive_rules1">Button Two</button>
jQuery
$(".same").click(function(){
var url = $(this).attr("data");
//alert(url);
$.ajax ({
url: url+".php",//pass the url here or you can use whatever I used .php. And do the other stuff etc.
});
});
For more go to my JSFILLDE
If you need my help. Please find me any of social network by searching yeshansachithak.
Here Is Your Code - As You Want - For more explain
<table>
<tr>
<td><b>+ New Rule</b></td>
<td><input type="text" name="Keyword" id="keyword" style="width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type="button" data="your_file_name" value="Verify" class="Buttons deriver" rel="<?php echo $_GET['id']; ?>"/></td>
<td><input type="button" data="your_file_name" value="Add" class="Buttons deriver" rel="<?php echo $_GET['id']; ?>"/></td>
</tr>
</table>
Just pass another attribute in your <button data="your_file_name" ...... Then use your ajax call as like you did. Your button class is driver. Please see below.
<script>
$(document).ready(function() {
$(".deriver").click(function() {
//Edit by Yesh
var url = $(this).attr("data");
//To check
alert(url);
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
//url: 'derive_rules.php', //Edit by Yesh
url: url+'.php',//You can use whatever extension (.html ect..)
data: 'kw='+val+'&agent='+agent,
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
if(data.success == 'true') {
$("#results_holder").show();
$("#results").html(data.msg);
$("#keyword").val('');
}
else {
alert(data.msg);
}
}
});
}
});
});
</script>
Thanks dude.
If you need my help. Please find me any of social network by searching yeshansachithak.
look at classes on button , need to change selector
$(document).ready(function() {
$(".deriver0").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules.php',
data: {kw:val,agent:agent},
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
alert(data);
}
});
}
});
$(".deriver1").click(function() {
var val = $("#keyword").val();
var agent = $(this).attr('rel');
if(val == '') {$("#keyword").focus(); return;}
else {
$.ajax ({
url: 'derive_rules1.php',
data: {kw:val,agent:agent},
type: 'GET',
dataType: 'json',
cache: 'false',
success: function(data) {
alert(data);
}
});
}
});
});
</script>
<td><b>+ New Rule</b></td>
<td><input type = "text" name = "Keyword" id = "keyword" style = "width:300px" placeholder = "Keyword or Phrase"/></td>
<td><input type = "button" value = "Verify" class = "Buttons deriver deriver0" rel = "<?php echo $_GET['id']; ?>"/></td>
<td><input type = "button" value = "Add" class = "Buttons deriver deriver1" rel = "<?php echo $_GET['id']; ?>"/></td>
</tr></table>

How to delete all entry from table using checkBox clickall after confirmation is true? jQuery Ajax PHP

I am trying to delete all records from the table using the checkbox. When the user checked the topmost checkbox, it will check all other checkboxes inside the loop then a confirmation box will appear about deleting the records. if the user click OK, the the all the records will be deleted using $.ajax, if he clicked Cancel, then, the page will return to the same state, and the checkboxes are not checked anymore.
<?php
include 'dbconn.php';
?>
<table border="1" >
<tr><td align="center" width="20"><input type="checkbox" name='checkALL' id='checkALL'></td><td>Name</td>
</tr>
<?php
$sql=mysql_query("SELECT * FROM names ORDER BY names ASC") or die(mysql_error());
while($rows=mysql_fetch_assoc($sql)){
?>
<tr>
<td><input type="checkbox" name="id[]" id="id[]" value="<?php print $rows['id'];?>">
</td><td>Name</td>
</tr>
<?php
}
?>
</table>
JQUERY
<script>
$(function(){
//click all
$('#checkALL').click(function(){
$(':checkbox').attr({checked: 'true'});
var del=confirm("You checked all the box. Delete All?");
if(del==true){
//delete here using $.ajax
}
else{
window.location.reload(false);
$('#checkAll').attr({checked: 'false'});
}
});
});
</script>
Place this in your if block.
$.ajax({
type: "GET",
url: '<php file which truncates table>',
success: function (data) {
if (data == 'truncated') {
alert('success');
} else {
alert('not truncated');
}
}
});
Return the string truncated from your php file on success.
Here U- PageUrl, A- Action on page, P- Parameter
if (confirm('Are you sure to delete this record?')) {
Operation(U, A, P);
}
function Operation(U, A, P) {
$.ajax({
type: "POST",
url: U + '/' + A,
data: P,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
}
});
}
You can use something like this in your HTML check all page
<html>
<head><title>Select/Delete ALL with jQuery/PHP</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<table border="1" cellpadding="5">
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="100" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="200" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="300" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
var checked = false;
$('#checkAll').click(function(){
if (checked == false){
checked = true
} else {
checked = false
}
$('input.check').attr("checked",checked);
var confirmDelete=confirm("You checked all the box. Delete All?");
if (confirmDelete==true){
var csv = '';
$('.check').each(function() {
csv += $(this).attr("value") + ",";
});
$.ajax({
type: "POST",
url: "delete.php",
data: { tobeDeleted: csv }
}).done(function( msg ) {
console.log( "Data has been deleted: " + msg );
});
} else {
$('#checkAll').attr("checked", false);
$('input.check').attr("checked", false);
}
});
});
</script>
</body>
</html>
and use something like this in your PHP script
<?php
$postDeleted = substr($_POST['tobeDeleted'], 0, strlen($_POST['tobeDeleted'])-1);
$arrDeleted = explode(",", $postDeleted);
$sql = "DELETE FROM employee WHERE 1=1 ";
foreach($arrDeleted as $key=>$value){
$sql .= "OR employee_id = $value ";
}
echo $sql;
?>
if(del==true){
$.ajax({
type: "POST",
url: 'your_file_url',
async:false,
cache: false,
success: function(data){
if (data == 1) {
alert('success');
} else {
alert('Error');
}
}
});
}
In your php file, echo 1 for successful delete and 0 for some error

jQuery Remove tr after ajax success

I am trying to remove table row after successful ajax call, but it is not working. No errors in firebug, it deletes the row on the back-end PHP, just doesnt remove the tr. Here is my code:
function closelead(rowid){
var rowid = rowid;
$.ajax({
type: "POST",
url: "ajax/close.php",
data: "rowid="+ rowid,
success: function(html){
$(this).closest('tr').remove();
}
});
}
and the html:
<table id="companytable">
<tr id="top"><th>Business Name</th><th>Phone</th><th>Carrier</th><th>X-Date</th><th></th><th></th><th></th></tr>
<?php
$query = "SELECT * FROM leads WHERE user = '$user' ORDER BY wccompcode";
$selectlead = mysql_query($query)or die(mysql_error());
while($leadlist = mysql_fetch_array($selectlead)){
$compcode = $leadlist['wccompcode'];
$compcode = sprintf("%03s", $compcode);
$selcomp = mysql_query("SELECT carname FROM carrierlist WHERE carcode = '$compcode'")or die(mysql_error());
while($carrier = mysql_fetch_array($selcomp)){
$carrier1 = $carrier['carname'];
}
?>
<tr id="<?php echo $leadlist['ID'];?>"><td id="busname"><?php echo $leadlist['busname'];?></td><td><?php echo $leadlist['phone'];?></td><td><?php echo $carrier1;?></td><td><?php echo date("m/d/Y",strtotime($leadlist['wcxdate']));?></td><td><input type="button" value="Call Back" class="searchbutton" /></td><td><input type="button" onclick="closelead(<?php echo $leadlist['ID'];?>)" value="Close" class="searchbutton" /></td><td><input type="button" value="Soft Quote" class="searchbutton" /></td></tr>
<?
}
?>
</table>
Try
function closelead(rowid){
var rowid = rowid;
$.ajax({
type: "POST",
url: "ajax/close.php",
data: "rowid="+ rowid,
success: function(html){
$('#'+rowid).remove();
}
});
}
function closelead(rowid){
var rowid = rowid;
$.ajax({
type: "POST",
url: "ajax/close.php",
data: "rowid="+ rowid,
success: function(html){
$('#'+rowid).closest('tr').remove();
}
});
}

Categories