multiple select with checkbox in php - php

i am making a website in which i am to embbed the functionality of delete using multiple checkbox. here is my code. my problem is
1. Ajax call is not working.
2. how can i make search from database for array .
<?php
if(isset($_POST['Delete']))
{
$array=$_POST['check_box'];
}
?>
<form method="post" id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while($selectnumberarr=mysql_fetch_array($selectnumber))
{
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" id="<?php $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}?>
<input type="submit" name="Delete" id="delete">
</table>
</form>
and below is my ajax and javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
any help would be appriciated

your code is almost correct. You need to remove `onChange="show()" for input checkbox, because if you have jquery then you don't need to put events on HTML elements.
Use jquery 'on' method for compatibility for latest php library.
Replace your jquery code with following jquery code :-
<script>
$(document).ready(function(){
$('#delete').on('click',function()
{
var cat_id = $('.check_box:checked').map(function() {
return this.id;
}).get().join(',');
console.log(cat_id);
$.ajax({
type: "POST",
url: "checkbox.php",
data: { "kw ":cat_id },
datatype:'json',
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
Use ".check_box" instead of "element" in jquery to prevent checks for all checkboxes, instead of desired ones.
Hope it helps.

Why you don't use an array for sending the checkboxes like:
HTML part:
<?php
if (isset($_POST['check_box'])) {
var_dump($_POST['check_box']);
echo "ajax call is working";
}
?>
<form id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while ($selectnumberarr = mysql_fetch_array($selectnumber)) {
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" value="<?php echo $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}
?>
</table>
<input type="button"name="delete" id="delete" value="Delete" />
</form>
JQuery part:
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
So you can easily get an array of the selected checkboxes in php with:
$idsArray = $_POST["check_box"];
this looks now like:
array(
"1", "2","etc.."
);
so this array contains all the ids of the selected checkboxes for delete.

Related

Deleting a Record from MySQL Using Ajax

There's something wrong with my codes and I'm unable to run it successfully. When I debug my Ajax code using Google Developer tools, Ajax data parameter has the value of the primary key (uid) but it seems it doesn't send POST request to delete.php. I've no idea what the problem is.
Thanks for your helps and suggestions in advance!
index.php: Press Delete Button to Fire Ajax Code
<tbody>
<!--Populate HTML Table-->
<?php if(!empty($records)) {
foreach ($records as $record) {
?>
<tr>
<td data-target="rowNum"></td>
<td data-target="userId" style="display: none;">
<?php echo $record['uid']; ?>
</td>
<td data-target="firstname"><?php echo $record['first_name']; ?></td>
<td data-target="lastname"><?php echo $record['last_name']; ?></td>
<td data-target="emailaddress"><?php echo $record['email_address']; ?></td>
<td>
<button class="btnEdit">Edit</button>
<!--Press Delete Button to Fire Ajax Code-->
<button class="btnDelete">Delete</button>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
Ajax Code: Send userId (Table Primary Key) as Data to Delete.php
$(document).ready(function(){
$(".btnDelete").click(function(){
var userId = $(this).closest("tr").children("td[data-target=userId]").text();
$.ajax({
url: "delete.php",
type: "POST",
data: userId
});
});
});
delete.php:
<?php
include 'database.php';
$conn->query("DELETE FROM Users WHERE uid = '$_POST['userId']'");
?>
You pass your data like this:
$.ajax({
url: "delete.php",
type: "POST",
data: userId
});
userId value is probably just a scalar without key that you're trying to use in delete.php. So change this code to:
$.ajax({
url: "delete.php",
type: "POST",
data: { userId: userId }
});
and it should work.
this might help, you are send data as text.
$(document).ready(function(){
$(".btnDelete").click(function(){
var userId = $(this).closest("tr").children("td[data-target=userId]").text();
$.ajax({
url: "delete.php",
type: "POST",
contentType: 'text/plain'
data: {userId:userId}
});
});
});
You can probably get it to run the way you are trying to but here's a way that makes a bit more sense to me:
<tbody>
<!--Populate HTML Table-->
<?php if(!empty($records)) {
foreach ($records as $record) {
?>
<tr>
<td data-target="rowNum"></td>
<td data-target="firstname"><?php echo $record['first_name']; ?></td>
<td data-target="lastname"><?php echo $record['last_name']; ?></td>
<td data-target="emailaddress"><?php echo $record['email_address']; ?></td>
<td>
<button class="btnEdit">Edit</button>
<!--Press Delete Button to Fire Ajax Code-->
<form class="deleteForm" method="POST">
<input type="hidden" name="userId" value="<?= $record['uid'] ?>" />
<button type="submit" class="btnDelete">Delete</button>
</form>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
Then in JavaScript
$(document).ready(function(){
$(".deleteForm").on('submit', function(){
var data = $(this).serialize(); // Let jQuery prepare the data
$.ajax({
url: "delete.php",
type: "POST",
data: data
});
return false; // Cancel default
});
});
Lastly:
<?php
include 'database.php';
$userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT); //Assuming an ID is an int, in general be cautions of SQL injection.
if ($userId) {
$conn->query("DELETE FROM Users WHERE uid = '$_POST['userId']'");
} else {
http_response_code(400); // Missing the input
die();
}
?>

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

using jquery each method with ajax

I'm trying to display a list of players with a edit button next to each one. When edit is pressed, then the user can edit that player. I'm trying to do this using ajax. The problem: The table will display for a split second then it's a blank screen.
<?php foreach($players as $player): ?>
<tr>
<td><?= $player['first_name']; ?></td>
<td><?= $player['last_name']; ?></td>
<td><?= $player['email']; ?></td>
<td align="center" >
<form action="" method="post" id="edit_player">
<input type="hidden" name="user_id" value="<?= player['user_id']; ?>">
<input type="submit" value='Edit' name='submit'>
</form>
</td>
</tr>
<?php endforeach;?>
Here is my jquery/ajax code. I made some changes from earlier. I think it's better, but it's still not working.
$(document).ready(function() {
var contents = $('#teamMain');
$('.edit_player').each(function(index, value) {
var formData = $(this).attr('user_id');
$.ajax({
url: 'views/team_nav.php',
type: 'POST',
cache: false,
data: formData,
success: function(data){
contents.html(data);
}
});
});
});

Submit form after form load is blank

I make index.php like this:
<script src="js/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$("#sload").load('save1.php',function(forma){
$(".csave").click(function(){
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
})
return false;
});
});
});
</script>
SAVE
<div id="sload"></div>
save1.php like this :
<table>
<form method="post" name="form1" id="form1" action="input1.php">
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</form>
and input1.php
<? session_start();
include "db.php";
$date=$_POST['date'];
$location=$_POST['location'];
mysql_query("insert into hal (date,location) values ('$date','$location')");
?>
after I click SAVE not an error, but the database is stored in an empty field. Submit form after form load is blank
Thanks.
You need to separate the logic of loading and saving like this:
Here's an example (based on your code) as a single page script test.php:
<?php
// Load Form
if (isset($_GET['loadForm']))
{
exit('<form method="post" name="form1" id="form1" action="test.php">
<table>
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</table>
</form>');
}
// Handle Form Save
if (count($_POST) > 0)
{
// TODO
exit('got form data: '. print_r($_POST, true));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Load Form
$('#sload').load('test.php?loadForm');
// Handle Save Click
$('.csave').click(function()
{
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
});
});
});
</script>
SAVE
<div id="sload"></div>
When I click save, this is what the output is:
To complete this code, add the db row inserting code where it says TODO. Hope this helps.
Update
Here's the split version:
index.php
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Load Form
$('#sload').load('save1.php');
// Handle Save Click
$('.csave').click(function()
{
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
});
});
});
</script>
SAVE
<div id="sload"></div>
save1.php
<form method="post" name="form1" id="form1" action="input1.php">
<table>
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</table>
</form>
input1.php
<?php
session_start(); // what's this for? you aren't using session on this file
// this is not safe! use mysqli or pdo and escape post values!!!
include "db.php";
$date=$_POST['date'];
$location=$_POST['location'];
mysql_query("insert into hal (date,location) values ('$date','$location')");
?>

jquery post form

I have this code for send simple data using jquery , but no works , all time reload de page and no load contents i send by post
My code it´s this :
<script>
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
</script>
<form name="forma" id="form_order" method="post" action="">
<table width="100%" border="1">
<tr>
<td height="30" align="center" valign="middle">
<select name="select_order">
<option value="articles">Articles</option>
<option value="blogs">Blogs</option>
<option value="products">Products</option>
</select>
<input type="submit" name="Submit" value="Acceder">
<input type="hidden" name="send_order2" value="ok">
<input type="hidden" name="action_load" value="<?php echo $_REQUEST['action_load'];?>">
</td>
</tr>
<tr>
<td height="30" align="center" valign="middle"> </td>
</tr>
</table>
</form>
<div id="load_order"></div>
In the div called load_order , it must load the result of this send by post from the form , but the page reload and no works , i see the code many times but i don´t understand what happen
Thank´s for All
There is a syntax error in your code, you haven't closed the submit handler.
$(document).ready(function() {
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "indexer_adm.php?send_order2=ok",
success: function(data){
$("#load_order").html(data);
}
});
return false;
}); // <---
});
Try returning false inside of the submit block, rather than of the ready block.
You may have a syntax error since return false should stop the form from refreshing. I would use the post function instead:
<script>
$(function() {
$("#form_order").submit( function () {
$.post('indexer_adm.php?send_order2=ok', $(this).serialize(), function(data) {
$("#load_order").html(data);
});
return false;
});
</script>
Ok !!! , Thank´s everybody
The Right code :
<script>
$(document).ready(function() {
/*
$("#load_order").show(1000);
$("#load_order").load("<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>");
*/
$("#form_order").submit( function () {
$.ajax({
type: "POST",
data : $(this).serialize(),
cache: false,
url: "<?php print "".$ruta_path_adm."".$ruta_modulos."/mod_order/indexer_adm.php?send_order2=ok";?>",
success: function(data){
$("#load_order").html(data);
}
});
return false;
});
});
</script>
Thank´s for the help i put bad the script and no see this , thank´s

Categories