Deleting multiple rows from database by checkboxes - php

I want to delete multiple rows from database by checkboxes i have working script for "Check All" but when i want delete one or two , nothing happend.
JavaScript
<script type="text/javascript">
jQuery(function($) {
$("form input[id='check_all']").click(function() { // triggred check
var inputs = $("form input[type='checkbox']"); // get the checkbox
for(var i = 0; i < inputs.length; i++) { // count input tag in the form
var type = inputs[i].getAttribute("type"); // get the type attribute
if(type == "checkbox") {
if(this.checked) {
inputs[i].checked = true; // checked
} else {
inputs[i].checked = false; // unchecked
}
}
}
});
$("form input[id='submit']").click(function() { // triggred submit
var count_checked = $("[name='data[]']:checked").length; // count the checked
if(count_checked == 0) {
alert("Please select a comment(s) to delete.");
return false;
}
if(count_checked == 1) {
return confirm("Are you sure you want to delete these comment?");
} else {
return confirm("Are you sure you want to delete these comments?");
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.submit').click(function(){
var checkValues = $('input[name=data[]]:checked').map(function()
{
return $(this).val();
}).get();
$.ajax({
url: 'resources/ajax/ajax_delete_comment.php',
type: 'post',
data: { data: checkValues },
success:function(data){
}
});
});
});
</script>
HTML/PHP
<form method="post" id="form">
Check All <input type="checkbox" id="check_all" value="">
Here im displaying record from database and <input name=\"data[]\" type=\"checkbox\" id=\"data\" value=" . $row['id'] . ">
<input name="submit" class="submit" type="submit" value="Delete" id="submit">
</form>
DELETING SCRIPT
if(isset($_POST['data'])) {
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$sql = $db->query("DELETE FROM comments WHERE `id` = '$id'");
if ($sql)
{
echo "success";
}
else
{
echo "Failed to delete the comment.";
}
}}
So its work for check all, but when im checking one or two objects, nothing happend, maybe someone could help?

Javascript
Since you are using jquery there is better way :)
<script type="text/javascript">
var is_activate = true; // we will track which input button was clicked :)
jQuery(function($) {
$("#form input#check_all").change(function() {
var inputs = $("#form input[type='checkbox']");
if ( $(this).is(":checked") ) {
inputs.prop( "checked", true );
// inputs.attr( "checked", true ); // if its not working
}
else {
inputs.removeAttr( "checked" );
}
});
// Track clicked button
$("#form input[type=submit]").on("click",function(e) {
is_activate = ( $(this).hasClass("activate_btn") ) ? true : false;
});
$("#form").submit(function(e) {
e.preventDefault();
var string = ( is_activate ) ? 'activate' : 'delete';
var data = $(this).serialize();
var checked = $(this).find("input[name='data[]']:checked").length;
if ( checked == 0 ) {
alert( "Please select a comment(s) to "+string+"." );
return false;
}
var text = "Are you sure you want to "+string+" these comment"+( ( checked == 1 ) ? "?" : "s?" );
if ( confirm( text ) ) {
$.ajax({
url: 'resources/ajax/'+( ( is_activate ) ? 'ajax_activate_comment.php' : 'ajax_delete_comment.php' ),
type: 'post',
data: data,
success: function( data ) {
}
});
}
});
});
</script>
HTML
<form method="post" id="form">
<label>Check All</label>
<input type="checkbox" id="check_all" value="">
<label>Here im displaying record from database and</label>
<input name="data[]" type="checkbox" id="data1" value="1">
<input name="data[]" type="checkbox" id="data2" value="2">
<!-- Activate Button -->
<input class="activate_btn" type="submit" name="activate" value="Activate" id="submit">
<!-- Delete Button -->
<input class="delete_btn" type="submit" name="delete" value="Delete" id="submit">
</form>
PHP
A single query is enough :)
<?php
if ( isset( $_POST['data'] ) ) {
$id_array = $_POST['data'];
if ( !empty( $id_array ) ) {
$id_array = implode( ",", $_POST['data'] ); // dont forget to sanitize
$sql = $db->query( "DELETE FROM comments WHERE `id` IN (".$id_array.")" );
}
}
?>
And remember, its not good that doing this all in client side.
You can do POST request to a single file, since your each input button has a unique name.
So in your PHP code, you can find which button was clicked like this.
<?php
if ( isset( $_POST["activate"] ) ) {
$sql = $db->query( "UPDATE comments SET status = '1' WHERE `id` IN (".$id_array.")" );
}
else {
$sql = $db->query( "DELETE FROM comments WHERE `id` IN (".$id_array.")" );
}
?>
look how simple :) Isn't it?

Related

Submit form checkbox value without page refresh Ajax php

Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.
Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");

PHP + jQuery: ajax callback not working

I need your help to try to sort out an issue with ajax callback.
What happen is that the php script is called without issues, the query works fine and it generate the json output, but the callback doesn't works.
No div is displayed on success and no changes on class happens.
This is my form
<form class="form-inline">
<input type="hidden" id="id_pro" value="1">
<input type="hidden" id="status" value="1">
<button id="submit" type="button" class="btn btn-link">
<span id="check" class="glyphicon glyphicon-check" title="my tytle"></span>
</button>
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
This is the js part
$(function() {
$("#submit").click(function() {
var id_pro = $("#id_pro").val();
var status = $("#status").val();
var dataString = 'id_pro='+ id_pro + '&status=' + status;
if(id_pro=='' || status=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "myphppage.php",
data: dataString,
datatype: 'json',
success: function(data)
{
if(data.result=='1')
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#check").attr('class', data.check);
}
}
});
}
return false;
});
});
And this is the php part
<?
if($_POST)
{
$id_pro=$_POST['id_pro'];
$status=$_POST['status'];
if($status==0){$status=1;}else{$status=0;}
if ($mysqli->query("UPDATE mytable SET online=".$status." WHERE id=".$id_pro." ") === TRUE) {
header("Content-type: application/json");
$data = array('check'=>'new_class','check_text'=>'new text','result'=>'1');
print json_encode($data);
}
else
{
header("Content-type: application/json");
$data = array('result'=>'0');
print json_encode($data);
}
$result->close();
}else { }
?>
Any idea?
Thank you in advance
error 500 means error in php and in your php don't see defined $mysqli and $result i think here is your problem.
better PHP looks like this but must define connect to DB
<?php
header("Content-type: application/json");
$data = array('result'=>'0');
if ($_SERVER['REQUEST_METHOD'] == 'post' )
{
$id_pro = $_POST['id_pro'];
$status = ($_POST['status'] == 0) ? 1 : 0; // if($status==0){$status=1;}else{$status=0;}
// define $mysqli
if ($mysqli->query("UPDATE mytable SET online=".$status." WHERE id=".$id_pro." ") === TRUE) {
$data = array('check'=>'new_class','check_text'=>'new text','result'=>'1');
}
// $result->close(); // ????
}
print json_encode($data);

Input validation through AJAX

I have the following AJAX in my index.php:
$(document).ready(function() {
$('.buttono').click(load);
});
function load() {
$.ajax({
url: 'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data) {
$('#content').append(data);
});
}
HTML (part of index.php):
<form method="POST" action="">
<input type="text" name="input">
<input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>
And in my ajaxRequest.php I have the following PHP snippet:
if ($_POST['input'] == 'dog') {
echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
echo 'Status 2';
}
How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?
Well what I see in your code is that:
first you have not specified your request method,
second you have not set $_POST['dog']
I would have gone with this ajax:
$.ajax({
type : "POST",
url : 'to/url',
data : { input : $("input[name='input']").val() },
success : function(data){
// do whatever you like
}
});
What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:
<!-- HTML -->
<form method="POST">
<input type="text" id="type"/>
<button id="submit">Sumbit</button>
</form>
<!-- JS -->
$(document).ready(function(){
$('#submit').click(onSubmitClicked);
});
function onSubmitClicked(){
var data = {
"input": $('#type').val()
};
$.ajax({
type: "POST",
url: "url/To/Your/Form/Action",
data: data,
success: success
});
function success(data){
if(data == 'status 1'){
//Do something
}
}
}
Try this:
in you php file:
$res = array();
if ($_POST['input'] == 'dog') {
$res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
$res['status'] = '2';
}
echo json_encode($res);
Then in your jquery:
function load(){
$.ajax({
type : "POST",
data : { input : $("input[name='input']").val() },
url:'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data){
$('#content').append(data.status);
});
}

Check if the input data is already exists in the DB jquery

I have a form that adds device name and device id in mysql database. I have written a jquery script that will check whether the device id is already in the db. If exists it will return false. I have the following code-
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //newly added
$('#Submit').click(function() {alert('in');
var checkID = $('#device_id').val(); // assuming this is a input text field
$.post('includes/checkid.php', {'device_id' : checkID}, function(data) {
if(data=='exist') alert("already exists"); return false;
else $('#add_dev').submit();
});
});});
</script>
<form method="post" action="includes/process_add.php" name = "add_dev" id = "add_dev">
<tr><td width="150">Device ID</td><td>:<input type="text" name="device_id" id= "device_id"></td></tr>
<tr><td>Device Name</td><td>:<input type="text" name="device_name"></td></tr>
<tr><td></td><td><br><input type="submit" name="submit" id= "submit" value="Add device"></td></tr>
</form>
and checkid.php is -
<?php
include("connection.php");
$id = $_POST['device_id'];
$sql = mysql_query("SELECT device_id FROM devices WHERE device_id = '$id'");
if (mysql_num_rows($sql) > 0) {
echo "exist";
}else echo 'notexist';
?>
its not working..
Ajax is async, return false outside ajax success callback:
$(document).ready(function () { //newly added
$('#submit').click(function () {
alert('in');
var checkID = $('#device_id').val(); // assuming this is a input text field
$.post('includes/checkid.php', {
'device_id': checkID
}, function (data) {
if (data == 'exist') alert("already exists");
else $('#add_dev').submit();
});
return false;
});
});

PayPal Button is not clickable link in Prestashop

I have installed the PayPal module and added all of the API details. It appears on the page, however it cannot be clicked. Why could this be? The code, as viewed in the source, is this:
It looks a bit odd to me. Like the image should be linked to the form somehow?
Also tried it in sandbox mode and that doesn't work either.
<div id="HOOK_SHOPPING_CART_EXTRA">
<div id="container_express_checkout" style="float:right; margin: 10px 40px 0 0">
<img id="payment_paypal_express_checkout" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" alt="" />
<form id="paypal_payment_form" action="http://mydomain.com/store/modules/paypal/express_checkout/payment.php" data-ajax="false" title="Pay with PayPal" method="post" data-ajax="false">
<!-- Change dynamicaly when the form is submitted -->
<input type="hidden" name="quantity" value="1" />
<input type="hidden" name="id_p_attr" value="" />
<input type="hidden" name="express_checkout" value="cart"/>
<input type="hidden" name="current_shop_url" value="http://mydomain.com/store/index.php?controller=order&multi-shipping=0" />
<input type="hidden" name="bn" value="FR_PRESTASHOP_H3S" />
</form>
</div>
</div>
Fixed it myself. The required code that makes the button work was missing the header. If anyone else finds this page in the future, the code you need is:
$(document).ready( function() {
$('#payment_paypal_express_checkout').click(function() {
$('#paypal_payment_form').submit();
return false;
});
$('#paypal_payment_form').live('submit', function() {
var nb = $('#quantity_wanted').val();
var id = $('#idCombination').val();
$('#paypal_payment_form input[name=quantity]').val(nb);
$('#paypal_payment_form input[name=id_p_attr]').val(id);
});
function displayExpressCheckoutShortcut() {
var id_product = $('input[name="id_product"]').val();
var id_product_attribute = $('input[name="id_product_attribute"]').val();
$.ajax({
type: "GET",
url: baseDir+'/modules/paypal/express_checkout/ajax.php',
data: { get_qty: "1", id_product: id_product, id_product_attribute: id_product_attribute },
cache: false,
success: function(result) {
if (result >= '1')
$('#container_express_checkout').slideDown();
else
$('#container_express_checkout').slideUp();
return true;
}
});
}
$('select[name^="group_"]').change(function () {
displayExpressCheckoutShortcut();
});
$('.color_pick').click(function () {
displayExpressCheckoutShortcut();
});
var modulePath = 'modules/paypal';
var subFolder = '/integral_evolution';
var fullPath = baseDir + modulePath + subFolder;
var confirmTimer = false;
if ($('form[target="hss_iframe"]').length == 0) {
if ($('select[name^="group_"]').length > 0)
displayExpressCheckoutShortcut();
return false;
} else {
checkOrder();
}
function checkOrder() {
confirmTimer = setInterval(getOrdersCount, 1000);
}
function getOrdersCount() {
$.get(
fullPath + '/confirm.php',
{ id_cart: '7' },
function (data) {
if ((typeof(data) != 'undefined') && (data > 0)) {
clearInterval(confirmTimer);
window.location.replace(fullPath + '/submit.php?id_cart=7');
$('p.payment_module, p.cart_navigation').hide();
}
}
);
}
});

Categories