Page should be reloaded on submitting the button - php

I have the following php code:-
<?php
.....
......
if(isset($_POST['disable']))
{
foreach ( $_POST['users'] as $userid ) {
$wpdb->query("UPDATE ".$wpdb->prefix."usercontrol SET disable_status ='disabled'
WHERE ID = ".$wpdb->escape($userid));
}
}
?>
HTMl
-----
<input type="submit" value="<?php esc_attr_e('Disable'); ?>" name="disable"
id="disable" class="button-secondary action" />
This is the page:-
I need to simply refresh /reload the page, if the user didn't check in any of the check box.
now its throwing error. Need to write an else condition for "if(isset($_POST['disable']))"
Please help.

<?php
.....
......
if(isset($_POST['disable']))
{
if(isset($_POST['users'])) {
foreach ( $_POST['users'] as $userid ) {
$wpdb->query("UPDATE ".$wpdb->prefix."usercontrol SET disable_status
='disabled' WHERE ID = ".$wpdb->escape($userid));
}
}
}
?>
Form submit does reload the page, since in your case it's not bound to an AJAX call. Just added an isset that checks for any value for users in $_POST. Optionally, you can even add an else to display an informative message instead of a plain reload.

Related

Output $_POST Array Values Inside a While Loop For An Input Element (During Form Validation) — PHP

I have a form that submits images and their titles. It is set up to check for errors via PHP validations on the image title form input elements and output any errors inside each image component (i.e. the instance in the while loop that represents a certain image). This all works OK.
What I would like to do is have it so that when one or more title is filled out correctly, but there are errors on one or more other titles, the $_POST value of the incorrect input is echoed out in the input element so the user doesn't have to re-type it. This has been easy to do on other forms on the site because there is no loop involved, e.g. on a sign up form etc. On a singular instance I would just do <?php echo $image_title; ?> inside the HTML value attribute, which is set referencing $image_title = $_POST['image-title'];]
So my question is, how do I have it so the $image_title $_POST value instances that pass the validations are outputted in their respective <input> elements, when other instances of the $image_title variable fail. If all the checks pass and there are no errors the form is then processed with PDO statements. The form submission button is placed outside of the main loop so all images are processed in one go when all the information is correct. I have a hidden input element that outputs the database image ID for each image, which can be used as a key in a foreach loop of some type. The problem of course being I can't get a foreach loop to work as I would like.
NOTE: To make the code simpler I've removed all the code relating to the outputting the images themselves.
<?php
if(isset($_POST['upload-submit'])) {
$image_title = $_POST['image-title'];
$image_id = $_POST['image-id']; // value attribute from hidden form element
// checks for errors that are later outputted on each image component
forEach($image_title as $index => $title) {
$id=$_POST['image-id'][ $index ];
if(empty(trim($title))){
$error[$id] = "Title cannot be empty";
}
}
if (!isset($error)) {
try {
// update MySQL database with PDO statements
header("Location: upload-details.php?username={$username}");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
} else {
// prevents error being thrown before form submission if input elements are empty
$image_title = "";
}
?>
<form method="post" enctype="multipart/form-data">
<!-- IMAGE DETAILS COMPONENT - START -->
<?php
$user_id = $_SESSION['logged_in'];
$stmt = $connection->prepare("SELECT * FROM lj_imageposts WHERE user_id = :user_id");
$stmt->execute([
':user_id' => $user_id
]);
while ($row = $stmt->fetch()) {
$db_image_id = htmlspecialchars($row['image_id']);
$db_image_title = htmlspecialchars($row['image_title']);
?>
<div class="upload-details-component">
<?php
// output error messages from the validation above
if(isset($error)) {
foreach($error as $element_id => $msg) {
if($element_id == $id) {
echo "<p>** ERROR: {$msg}</p>";
}
}
}
?>
<div class="edit-zone">
<div class="form-row">
<!-- ** THIS IS THE INPUT ELEMENT WHERE I WOULD LIKE THE TITLE OUTPUTTED IF IT DOESN'T FAIL THE VALIDATION ** -->
<input value="<?php echo $image_title; ?>" type="text" name="image-title[]">
</div>
<div class="form-row">
<input type="hidden" name="image-id[]" value="<?php echo $db_image_id; ?>">
</div>
</div>
</div>
<?php } ?> <!-- // end of while loop -->
<!-- submit form button is outside of the loop so that it submits all of the images inside the loop in on go -->
<button type="submit" name="upload-submit">COMPLETE UPLOAD</button>
</form>
i think this is what you want:
<input value="<?php echo htmlentities($image_title); ?>" type="text" name="image-title[<?php echo $db_image_id; ?>]">
foreach ($_POST['image-title'] as $key => $value) {
$stmt->execute([
':image_id' => $key,
':image_title' => $value
]);
}
Edit: I have now created a minimized version and was able to test it successfully. I created the mysql table on my test-maschine to try it out. I hope this will help you now.
With <input name="img[id]" value="title"> an array will created with the following structure: $_POST['img'][id] = title. The id as array key and the title as array value. So the title is uniquely assigned to each id. The array can be walk through with a foreach key=>value loop.
Edit2: I added error checking. If the title is empty or is "testfail" for example, the title will not be written to the database. In addition, the input field keeps the last input (restore $_POST string).
<?php
$connection = new PDO(...);
$error = []; // declare empty array
if(isset($_POST['img'])) {
try {
$q = "UPDATE lj_imageposts SET image_title=:image_title
WHERE image_id = :image_id AND user_id = :user_id";
$stmt = $connection->prepare($q);
foreach($_POST['img'] as $key => $value) {
// here the error check, so that the wrong title
// is not written into the database
if(trim($value) === '' || $value === 'testfail') {
echo "Error image id $key title $value <br>";
$error[$key] = TRUE; // set error var with img-id
continue; // skip to next img, do not execute sql-stmt
}
$stmt->execute([
':image_id' => $key,
':image_title' => $value,
':user_id' => $_SESSION['logged_in']
]);
echo "Update image id $key title $value <br>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
<form method="post" enctype="multipart/form-data">
<?php
$q = "SELECT * FROM lj_imageposts WHERE user_id = :user_id";
$stmt = $connection->prepare($q);
$stmt->execute([':user_id' => $_SESSION['logged_in']]);
while ($row = $stmt->fetch()) {
$id = htmlentities($row['image_id']);
// check if error with img-id is set above
if(isset($error[$row['image_id']])) {
// if error, fill in title from previous post
$title = htmlentities($_POST['img'][$row['image_id']]);
} else {
// if no error, fill in title from database
$title = htmlentities($row['image_title']);
}
?>
<input type="text"
name="img[<?php echo $id; ?>]"
value="<?php echo $title; ?>"><br>
<?php
// alternative version
//echo '<input type="text" name="img['.$id.']" value="'.$title.'"><br>';
}
?>
<button type="submit" name="upload-submit">Test</button>
</form>
This is harder than it needs to be, because you can't uniquely identify a particular title input except by the order it appears on the form, with the associated hidden input beside it. You need to do some careful juggling to correlate the IDs from the database with the $index of the $_POST arrays, to make sure your tiles and IDs match. You do have that all working, but this seems fragile and not a good solution IMO. I'd suggest using the database IDs as your form input index values, rather than relying on the order they appear on the form, as I did in my answer to a previous question of yours.
You're already tracking errors with the associated DB ID. So when it comes to displaying the input values, you can just check if there is an error for that DB ID. If there is not, this input passed validation, and you can re-display the value from the current $_POST:
<form method="post" enctype="multipart/form-data">
<!-- ... your code ... -->
while ($row = $stmt->fetch()) {
$db_image_id = htmlspecialchars($row['image_id']);
$db_image_title = htmlspecialchars($row['image_title']);
// Start with the value in the DB, this will display first time
// through.
$value = $db_image_title;
// If there's been a POST, and there is no $error for this ID,
// we know it passed validation.
if (sizeof($_POST) && ! isset($error[$db_image_id])) {
$value = $_POST['image-title'][$db_image_id];
}
?>
<!-- ... your code ... -->
<div class="edit-zone">
<div class="form-row">
<!-- Now we can use whatever value we set above -->
<input value="<?php echo $value; ?>" type="text" name="image-title[]">
</div>
Side Note
There's no need to iterate over all your errors to find the one you want. If you have its ID, you can address it directly. Instead of this:
if(isset($error)) {
foreach($error as $element_id => $msg) {
// Note your code above does not show what $id is here,
// AFAICT it is the same as $row['image_id']
if($element_id == $id) {
echo "<p>** ERROR: {$msg}</p>";
}
}
}
You can simply do:
if (isset($error) && isset($error[$row['image_id']])) {
echo "<p>** ERROR: " . $error[$row['image_id']] . "</p>";
}

Add to cart / Remove from cart without refreshing the page

I am new at some things and I need help about my store page.
For each item you wanna add to the cart or remove from the cart, the page refreshs and it is really annoying if you wanna buy several items.
I have read that I could use AJAX, I have read a lot of methods and nothing worked for me.
What do I need to do in order to make it work?
These are my add / remove:
<form action="" method="post">
<input type="hidden" name="item_id" value="{sid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="atc" value="Añadir" class="sub-link">
</form>
<form action="" method="post">
<input type="hidden" name="item_id" value="{cid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="rfc" value="Remover" class="sub-link">
</form>
And this is the function handling the submit:
function add_to_cart() {
global $db, $db_data, $db_acc, $login;
if (!empty($_POST['atc']) || !empty($_POST['rfc'])
&& isset($_GET['page']) && isset($_GET['data'])
&& $_GET['page'] == "store_shop") {
$data = $_GET['data'];
$pos = strpos($data, "-");
if ($pos == TRUE) {
$ndt = explode("-", $data);
$d1 = clean($ndt[0]);
$d2 = clean($ndt[1]);
if ($d1 == FALSE) {
$d1 = 0;
}
} else {
$d1 = 0;
$d2 = 0;
}
$sqli = $db->query("SELECT id, rname, char_db FROM $db_data.realms WHERE id='$d1'");
$numi = $db->num($sqli);
$geti = $db->get($sqli);
$cdb = $geti['char_db'];
$sqla = $db->query("SELECT id, username FROM $db_acc.account WHERE username='$login'");
$geta = $db->get($sqla);
$acid = $geta['id'];
if ($numi == 1) {
$sqlc = $db->query("SELECT guid, account, name FROM $cdb.characters WHERE account='$acid' AND guid='$d2'");
$numc = $db->num($sqlc);
$getc = $db->get($sqlc);
if ($numc == 1) {
$item = clean($_POST['item_id']);
$parent = clean($_POST['parent']);
if (!empty($_POST['atc'])) {
$sqll = $db->query("INSERT INTO $db_data.cart (`realm`, `account`, `character`, `item`, `parent`) VALUES ('$d1', '$acid', '$d2', '$item', '$parent')");
} else if (!empty($_POST['rfc'])) {
$sqll = $db->query("DELETE FROM $db_data.cart WHERE id='$item'");
}
header("Location: ?page=store_shop&data={$data}");
} else {
header("Location: ?page=store_shop&data={$data}");
}
} else {
header("Location: ?page=store_shop&data={$data}");
}
}
}
Edit: I think I am missing some details:
After clicking "add" ("Añadir" in Spanish) o "remove" ("Remover" in Spanish), the page reloads and the item is added to the cart div.
When I try the solutions I have read in stackoverflow or in other website, most of them does not work for my store and the only thing I can get is to prevent the page from reloading but the cart does not update.
Maybe should I use a iframe in the cart div?
I am still reading about ajax but I can not get it by myself.
Try this out
Remove the submit button and call the function Add to cart and same for Remove from cart using onclick="addtocart()" in anchor tag
function addtocart(){
get 'sid' and 'parent' value from anchor tag using jquery
$.ajax({
type: 'POST',
url: '/cart/add.php',
data:{ 'sid':sid, 'parent':parent }
success : function(data) { alert('success'); }
});
}
This is a form when generally causes a page load unless the default onsubmit action is overridden and the override function causes a stopPropagation on the event object. AJAX requires JS in which an XMLHttpRequest object is created (or ActiveX for IE) and communicates with server without a refresh by default ( although it can be done programatically). Then your server could return JSON for example or some indicator as to whether the call was successful and erroneous and the client side can handle it accordingly

Submit button send value on same php script, trying to use session

I have searched a lot but cannot find a solution yet. Hope anyone can help me with it, I will really appreciate.
I use a php news page with session. PHP script displays 10 news and if there is more news, visitor suppose to click "Next" button (I try to make it work with tag, but it doesn't work with usual submit button either). Page refresh using same script adding a value to page. Everything seemed to work except session. $_SESSION['page'] does not add value. I always come back to Page1.
<?php session_start();?>
<?php
if(isset($_SESSION['page']) && isset($_POST['next'])){
$_SESSION['page']++;
}
if(isset($_SESSION['page']) && isset($_POST['previous'])){
$_SESSION['page']--;
}
else{
$_SESSION['page']=1;
}
....//code reading file with news, counting values etc. that work good
//I tried several options:
//Option:1
if ($l == "en") {
echo '<p class="sider_link">Page: '.$_SESSION['page'].'. Unread news: '.$news_left;
echo '<form action="../en/news.php" method="post">';
echo '<a class="sider_link" href="#" name="next" onclick="this.form.submit()">Next Page</a></form></p>';
}
//Option:2
if ($l == "en") {
echo '<p class="sider_link">Page: '.$_SESSION['page'].'. Unread news: '.$news_left;
echo '<form action="../en/news.php" method="post">'
echo '<input type="hidden" name="next" value="yes" />';
echo '<a class="sider_link" href="#" onclick="this.form.submit()">Next Page</a></form></p>';
}
Your first statement works, page is increment. But after the second statement is false, the else condition is called. Page is set to one. To sum up you have an error in your condition.
if(isset($_SESSION['page']) && isset($_POST['next'])){
$_SESSION['page']++;
}
if(isset($_SESSION['page']) && isset($_POST['previous'])){
$_SESSION['page']--;
}
else{
$_SESSION['page']=1;
}
To
if(isset($_SESSION['page']) && isset($_POST['next'])){
$_SESSION['page']++;
}
else if(isset($_SESSION['page']) && isset($_POST['previous'])){
$_SESSION['page']--;
}
else{
$_SESSION['page']=1;
}

checkbox onclick in php function

Can i write some code to execute while my check box is checked in my php code..
my declaration of check box is...
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>
i thought to perform a function called check() while clicking the check box..
<script type="text/javascript">
function check(cb)
{
if($("input[type=checkbox]:checked"")
{
//my functionality and operations
}
}
But its not working, how can i perform the onclick event in the Checkbox's action..
First of all, there's a mistake. It should be .is(":checked").
function check(cb)
{
if($(cb).is(":checked"))
{
//my functionality and operations
}
}
And the HTML should be:
<input type="checkbox" onclick="check(this);" />
Or, if you wanna invoke a PHP Function after clicking on Checkbox, you need to write an AJAX code. If this is the case, in your if condition, and checked condition, you can call a PHP file, that calls only this function.
function check(cb)
{
if($(cb).is(":checked"))
{
$.getScript("clickCheckbox.php");
}
}
And you can write JavaScript plus PHP in the clickCheckbox.php file, say something like this:
clickCheckbox.php
<?php
header("Content-type: text/javascript");
unlink("delete.png");
echo 'alert("Deleted!");';
?>
Once you click on the checkbox, and if the state is checked, it gives out an AJAX call to this PHP file, where you are deleting a file delete.png and in the echo statement, you are outputting a JavaScript alert, so that you will get an alert message saying Deleted!.
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
Where your form has id myform
use
if ($('#checkbox').is(':checked'))
or inside an event
$('#checkbox').click(function(){
if ($(this).is(':checked')){
//your routine here if checked
}else{
//routine here if not checked
}
});
You can put like this:
Include the column checked in your table with default value NO.
Then after your SELECT statement show the array.
page1.php
<input type=checkbox value="<?php $row['checked']?>" onclick="location.href = 'update.php?id=<?php echo $row['id']; ?>&checked=<?php if ($row['checked'] == 'YES') { ?>NO<?php } else {?>YES<?php } ?>';" <?php if ($row['checked'] == 'YES') { ?> checked <?php } ?>>
update.php
<?php include('server.php'); ?>
<?php
$id = $_GET['id'];
$checked = $_GET['checked'];
if(isset($_GET['id']))
{
$sql = "UPDATE table SET
checked = '$checked'
WHERE `id` = '$id' ";
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error updating record: " . $conn->error;
}
header('location: page1.php');
}
?>
Try this one
<input id="checkbox" name="click" type="checkbox" onclick="check()"/>
//in js
if( $('input[name=checkbox]').is(':checked') ){
// your code
}

PHP Value for HTML Checkbox

I have a function that sets and unset's a $_SESSION variable depending on what was submitted from the form in my main page.
function if statement:
$_SESSION['search'] = true;
if($_POST['searchtv']){
$_SESSION['searchtv'] = true;
} else {
unset($_SESSION['searchtv']);
}
if($_POST['searchmovie']){
$_SESSION['searchmovie'] = true;
} else {
unset($_SESSION['searchmovie']);
}
The searchtv and searchmovie $_POST variables are set through the below checkboxes:
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
However the checked value always seems to be false and displays '' so no "checked" is set to display the tick in the box.
I do know that the $_SESSION variable is being set correctly however because in the same file i have another IF statement (below) that works 100%.
if(isset($_SESSION['searchtv'])){
$database->searchTV($_GET['show'], $session->uid);
}
if(isset($_SESSION['searchmovie'])){
$database->searchMovies($_GET['show'], $session->uid);
}
if(!isset($_SESSION['searchtv']) && !isset($_SESSION['searchmovie'])){
$database->searchTV($_GET['show'], $session->uid);
$database->searchMovies($_GET['show'], $session->uid);
}
If i only tick the searchtv checkbox it only runs the searchTV function and so on.. so i know it is being set and works.. just cannot get the feedback to the checkbox to say yes it was ticked when the search button was selected.
#medoix: Try changing this
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
to this
<input type="checkbox" name="searchmovie" value="movie" <?php if (isset($_SESSION['searchmovie'])) { echo 'checked="checked" '; } ?>/>
You realize that the portion of the code that checks $_SESSION['searchtv'] && $_SESSION['searchmovie'] near the bottom are both !isset. It'll only run if both aren't checked, rather than if they are.

Categories