I'm trying to implement a form that utilizes jquery's post feature to dynamically update the database. What I'm realizing is that after the user clicks the "update" button, the success function is called back just fine with a "Update successful" message.
The issue I have for the stackoverflow world is why on subsequent clicks (w/o refreshing the page) I'm not getting this same success message. Also, ironically my database is being updated, so I know the AJAX call is going through.
I've posted my code below:
JS
var TEAM = {
update: function() {
var form_data = $('form').serialize();
$.ajax({
type: "POST",
url: "../manager/edit_team.php",
data: form_data,
error: function() {
$('#status').text('Update failed. Try again.').slideDown('slow');
},
success: function() {
$('#status').text('Update successful!');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
},
cache: false
});
}
}
// jQuery Code for when page is loaded
$(document).ready(function()
{
$("#update").on("click", function() {
TEAM.update();
});
});
PHP (I welcome any other comments as well)
require '../includes/config.php';
include '../includes/header.html';
// autoloading of classes
function __autoload($class) {
require_once('../classes/' . $class . '.php');
}
// Site access level -> Manager
$lvl = 'M';
// Assign user object from session variable
if (isset($_SESSION['userObj']))
{
$manager = $_SESSION['userObj'];
}
else
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Establish database connection
require_once MYSQL2;
// Assign Database Resource to object
$manager->setDB($db);
// Authorized Login Check
if (!$manager->valid($lvl))
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Check for a valid game sch ID, through GET or POST:
if ( (isset($_GET['z'])) && (is_numeric($_GET['z'])) )
{
// Point A in Code Flow
// Assign variable from myteams-m.php using GET method
$id = $_GET['z'];
}
elseif ( (isset($_POST['z'])) && (is_numeric($_POST['z'])) )
{
// Point C in Code Flow
// Assign variable from edit_team.php FORM submission (hidden id field)
$id = $_POST['z'];
}
else
{
// No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
$team = new ManagerTeam();
$team->setDB($db);
$team->setTeamID($id);
$team->pullTeamData();
$flag = 0;
echo $flag . "<br />";
// Confirmation that form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{ // Point D in Code Flow
// Assume invalid values:
$tname = FALSE;
// Validate team name
if ($_POST['tname'])
{
$tname = $_POST['tname'];
}
else
{
echo '<p class="error"> Please enter a team name.</p>';
}
// Validate about team information
if ($_POST['abouttm'])
{
$abtm = trim($_POST['abouttm']);
}
else
{
$abtm = '';
}
// Check if user entered information is valid before continuing to edit game
if ($tname)
{
if($team->editTeam($tname, $abtm) == True)
{
echo '<p>Team was successfully updated</p>';
$flag = 1;
}
else
{
echo '<p>No changes were made</p>';
$flag = 2;
}
}
else
{ // Errors in the user entered information
echo '<p class="error">Please try again.</p>';
}
} // End of submit conditional.
echo $flag . "<br />";
// Point B in Code Flow
// Always show the form...
// Get team name attribute
$team->pullTeamData();
$teamname = $team->getTeamAttribute('tmname');
$about = $team->getTeamAttribute('about');
if ($teamname != '') // Valid user ID, show the form.
{
// Headliner
echo '<h2>Edit Team</h2>';
// Create the form:
echo '
<div id="EditTeam"></div>
<div id="Team">
<fieldset id="TeamDetails">
<legend>Edit Team</legend>
<form method="post" id="information">
<p id="status"></p>
<input type="hidden" name="z" value="' . $id . '" />
<p>
<label for="tname">New Team Name:</label><br/>
<input type="text" name="tname" id="tname" size="10" maxlength="45" value="' . $teamname . '" />
</p>
<p>
<label for="abouttm">Team Information:</label><br/>
<textarea id="abouttm" name="abouttm" cols="30" rows="2">"' . $about . '"</textarea><br />
<small>Enter something cool about your team.</small>
</p>
<p>
<input type="hidden" name="id" id="id">
<input type="button" value="update" id="update" />
</p>
</form>
</fieldset>
</div>';
}
else
{ //Not a valid user ID, kill the script
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
// Close the connection:
$db->close();
unset($db);
include '../includes/footer.html';
?>
You'll notice I also have a $flag defined to help with the debugging, but ironically it outputs 0 no matter the number of clicks to the "update" button. So there's no indication that the database is being updated, yet when I check the tables it certainly is.
I appreciate any help or pointers. Thanks,
#status message is not showing because you've hidden it by slideUp(), to show it again you need to slideDown() them.
success: function() {
$('#status').text('Update successful!');
-ADD-> $('#status').slideDown('slow');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
Do it same way as you have done in error handler:
success: function(){
$('#status').text('Update successful!').slideDown('slow');
...
It seems that you know it already and just forgot it...
Other method that may be useful is stop() to make sure that previous animation is stopped when new one is starting., especially important when using long timeouts/animations.
(useful = can prevent other problems with visibility and makes sure that messages does not start jumping in and out)
(long = somewhere around 0,5-1,5 sec or more, if during this time can happen something else then it is long...)
For example, this will clear fx queue, finish running animation immediately and slideUp():
$('#status').stop(true, true).slideUp('slow');
You also asked suggestions for other parts of code
If you are using same code at least twice or if it is general method that could be reused make it reusable:
function redirect_to( $page ) {
session_unset();
session_destroy();
$url = BASE_URL . $page;
ob_end_clean();
header("Location: $url");
exit();
}
if ($condition == true) {
redirect_to( 'index.php' );`
}
Related
We need to create a program that lets the user input the array size, their name, and age (depending on the array size the user entered). After that, we need to display all the elements of the array.
This is my code, but I'm having a problem adding a new element for another user and displaying it.
<html>
<head>
<title> PHP Array </title>
</head>
<body>
<form method="post" action="example.php">
<h3> Please enter the your information: </h3>
Array Size: <input type="text" name="arraysize"/> <br/><br>
Name: <input type="text" name="name" /><br/><br/>
Age: <input type="text" name="age"/> <br/><br/>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="cancel" value="Cancel"/><br/><br/>
<?php
if(isset($_POST['submit'])){
if((!empty($_POST['name'])) && (!empty($_POST['age'])) && (!empty($_POST['arraysize']))){
$info = array($_POST['arraysize'], $_POST['name'], $_POST['g6ave']);
$arraylength = count($info);
for ($i=0; $i<=$arraylength ; $i++) {
$name = $_POST['name'];
for ($j=1; $j<=$i; $j++){
echo "User's Name" .$i. ": " .$name. [$j] ."<br>";
$age = $_POST['age'];
for($k=0; $k<=$i; $k++){
echo "User's Age: " .$age. [$k] ."<br/>";
}
}
}
}
}
?>
</body>
</html>
One approach (of other possible approaches) below should give you the main ideas. I also commented the aim of the each script part.
Approach below assumes that you'll use same URL for all your form pages. (1st, 2nd and the success page)
I hope this helps.
session_start(); //Start new or resume existing session
if (isset($_SESSION['form_success']) && $_SESSION['form_success'] === true)
{
require 'success_page.php';
unset($_SESSION['form_success']); // don't needed anymore
return; //not to continue to execute the code
}
// decide the page from user
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
// display the first form page for the 1st time
require 'first_page_form.php';
return; //not to continue to execute the code
}
// if the first page was submitted.
if ($page === 'first') // or a specific POST flag from 1st page
{
//verify data from first page
$warnings = [];
if (first_page_data_valid() === true)
{
require 'second_page_form.php';
return; //not to continue to execute the code
}
// populate $warnings during first_page_data_valid()
//if first page data are invalid
print_r($warnings);
require 'first_page_form.php'; //display again
return; //not to continue to execute the code
}
// if the second page was submitted.
if ($page === 'second') // or a specific POST flag from 2nd page
{
//verify data from second page
$warnings = [];
if (second_page_data_valid() === true) // populate $warnings during second_page_data_valid()
{
// do things. ex: DB operations.
if (db_actions_success() === true)
{
$_SESSION['form_success'] = true; // defined and set to true.
// PHP permanent URL redirection. usage of 301 is important.
// it clears POST content. Prevents F5/refresh.
header("Location: https://www.url.com/form.php", true, 301);
exit; // good/recommended to use after redirect
}
else
{
echo 'System down or I have a bug. Try again later.';
return; //not to continue to execute the code
}
}
//if second page data is invalid
print_r($warnings);
require 'second_page_form.php'; //display again
return; //not to continue to execute the code
}
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
function that runs when i want to edit a client status.
// deletes (sets inactive) client
function setClientStatus($client) {
if ($_GET['action'] == "setinactive") {
//database functions
$sql = 'UPDATE clients SET active="0" WHERE id="'. $client .'"';
$result = query($sql);
confirmQuery($result);
//set message to user to display
$_SESSION['error'] = false;
$msgs[] = "Client was set to inactive and removed from the list!";
$_SESSION['userMsg'] = $msgs;
}
if ($_GET['action'] == "setactive") {
//database functions
$sql = 'UPDATE clients SET active="1" WHERE id="'. $client .'"';
$result = query($sql);
confirmQuery($result);
//set message to user to display
$_SESSION['error'] = false;
$msgs[] = "Client was successfully restored!";
$_SESSION['userMsg'] = $msgs;
}
//display clients page with changes made
redirect('?page=clients');
}
function that displays the message.
//function that shows message and styles accordingly
function message($msgs) {
if(!empty($msgs)) {
foreach ($_SESSION['userMsg'] as $msg) {
if ($_SESSION['error'] == false) {
echo '<div class="noError">'.$msg.'</div>';
} else {
echo '<div class="error">'.$msg.'</div>';
}
}
}
unset($_SESSION['userMsg']);
unset($_SESSION['error']);
echo "hello";
}
here is where i call it in my page....
div class="pageContainer">
<?php
//display messages
message($_SESSION['userMsg']);
?>
</div>
Now when everything is run and i select to edit and client status (or add client, edit client as they all have the same message section, just with different message) i can see the message displayed on the screen. i have a javascript script that will hid the message after 5 seconds, but it doesn't hide. after viewing the page source i notice that the section of code is not visible. again, i can see it clearly see the message that is suppose to be there "Client was set to inactive and removed from the list!" (or whatever message is set to display) but it is NOT show in the view source html.
pic of page loaded with message
here is the view source.....
<div class="pageContainer">
<div>
** updated **
this small example script renders the html, but my above script doesn't...
function setError() {
$error[] = "Password field is to short";
$_SESSION['userMsg'] = $error;
//return $_SESSION['msg'];
}
function message($errors){
if(!empty($errors)) {
foreach ($_SESSION['userMsg'] as $error) {
echo $error.'<br>';
}
}
unset($_SESSION['userMsg']);
}
If I get you right, you want to display $msgs, so why you iterate $_SESSION['userMsg'] ?
Probably the $_SESSION['userMsg'] is null or empty. If you want to display the $msgs just iterate it. And later add to session if really needed. In you code, you always unset the $_SESSION['userMsg'] in the end of function, probably it is always null then. I didn't see the $_SESSION['userMsg'] needed here :
//function that shows message and styles accordingly
function message($msgs) {
if(!empty($msgs)) {
foreach ($msgs as $msg) {
if ($_SESSION['error'] == false) {
echo '<div class="noError">'.$msg.'</div>';
} else {
echo '<div class="error">'.$msg.'</div>';
}
}
}
unset($_SESSION['error']);
echo "hello";
}
UPDATED
After reading your comments, this is related to javascript problem. You should add the id in <div> in order for it's works.
if ($_SESSION['error'] == false) {
echo '<div id="noError" class="noError">'.$msg.'</div>';
} else {
echo '<div id="error" class="error">'.$msg.'</div>';
}
I am developing a eCommerce website in php without any cms. I have done approx all things, but I am facing a problem in add to cart page. I want to display a successfully message after add to cart with session variable. Please suggest me.
Here is my code:
<?php
session_start();
include('dbfunctions.php');
$id = $mysqli->real_escape_string($_GET['id']);
$category_id=$mysqli->real_escape_string($_GET['category_id']);
?>
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$products=$mysqli->query("select * from product_details where id=$id and category_id='$category_id'");
if(count($products)>0)
{
$obj=$products->fetch_object(); {
echo '<form method="post" action="cart_update.php">';
echo '<img src="../image/product/'.$obj->pic.'"class="img-responsive" style="width:100%;height:300px;">';
echo ucwords($obj->product_name);
echo $obj->material;
echo $obj->product_code;
echo $obj->area;
echo $obj->width;
echo $obj->rolls;
echo $obj->features;
echo '<button id="button-cart">Add to Cart</button>';
echo '<input type="hidden" name="id" value="'.$obj->uid.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
}
}
?>
mysqli_query Returns FALSE on failure and for successful queries if will return TRUE. You can't use it for count
So instead of this
$products=$mysqli->query("select * from product_details where id=$id and category_id='$category_id'");
if(count($products)>0)
you need to count number of rows
$row_cnt = $products->num_rows;
if(count($row_cnt)>0)
if ($success){
$message = "Sent! Thank you";
} else {
$message = "Ops! Try again!";
}
?><script>
prompt(<?php echo json_encode($message); ?>);
</script>
<noscript>
<p><?php echo htmlspecialchars($message); ?></p>
</noscript>
Note: Given a string for input, json_encode will output a JavaScript string literal that is safe for inclusion in an HTML script element. It will not output JSON.
While the strings themselves don't contain any special characters, it is a good habit to run this sort of XSS protection against anything you output that isn't explicitly HTML/JS/etc.
Or try this
<?php
if ($success) {
$message = "Added! Thank you.";
} else {
$message = "Oops...";
}
echo '<div id="message">'.$message.'<div id="close-button"></div></div>';
?>
This way you can style your message like you want to (like positioning it absolutely). But you would have to implement the close button in javascript if the div is positioned absolute. I hope this helps
For display this type message toast is fit to your requirement.
http://codeseven.github.io/toastr/demo.html
You could use jQuery for this and ajax to your page as such:
jQuery
var itemName = $( "#itemName" ).val(); //Get the value using the ID of the input
var itemPrice = $( "#itemPrice" ).val(); //Get the value using the id of the input
$.ajax( {
url: "myphpscript.php?itemName=" + ietmName + "&itemPrice=" + itemPrice, //Specify your url to go to (an abosulte path to the php script to run)
type: "GET", //Specify the type, can be GET or POST
success: function ( response ) //Set the success function
{
if (response == "true") //Check the response it "true"
{
alert( "Item addded to cart!" ); //Show success message
return;
}
//response == "false" handler
alert( "Failed to add item to the cart" ); //Show fail message
return;
}
} );
PHP CODE
function addToCart()
{
if (!isset($_REQUEST['itemName']) || !isset($_REQUEST['itemPrice']))
{
return "false";
}
//Add to cart code with `return "true";` or `return "false"` checks
return "true";
}
I hope this goes some way to helping you :)
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
}