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>';
}
Related
After my form has been submitted and my message has been sent I want to go back to the index which this does, but I also want to display echo 'Message has been sent' in the index.php in a div instead of my process.php, how would I go about doing this. Sort of new to php if you need any more of my code I will provide or link to site. Thanks.
This is what i tried so far.
in my process.php file
if(!$mail->send()) {
$output = 1;
// $output = 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$output = 2;
header('Location:index.php');
}
in my index.php file
<?php
if ($output == 2) {
echo "<b>Message has been sent</b>";
} elseif ($output == 1) {
echo "<b>Message could not be sent, please try again</b>";
} else {}
?>
The variable $output isn't set in your index.php file.
As an easy way to start you can try it like
header('Location:index.php?output='.$output);
and fetch output in your index.php with
$output = $_GET['output'];
at the beginning of your file, that way you will be able to make your if statements work.
Also be advised that you will never be redirected if $output = 1 in your process.php, as the header is only in the else statement. Simply place the header after your else statements closing bracket.
if(!$mail->send()) {
$output = 1;
} else {
$output = 2;
}
header('Location:index.php?output='.$output);
die();
index.php:
<?php
if (isset($_GET['output'])) {
$output = $_GET['output'];
if ($output == 2) {
echo "<b>Message has been sent</b>";
} elseif ($output == 1) {
echo "<b>Message could not be sent, please try again</b>";
}
}
Please be advised that you shouldn't use unsanitized request data (user input and what so ever) in a production environment, as this is a security risk.
This won't work, the value won't get passed to the index this way:
} else {
$output = 2;
header('Location:index.php');
}
Your options (short of redesigning the way it works) are POST or GET;
} else {
$output = 2;
header('Location:index.php?sent=1');
}
Then in your index.php:
<?php
if (isset($_GET['sent']) && $_GET['sent'] == 1) {
echo "<b>Message has been sent</b>";
}
?>
Basically I want to add one last piece of validation, if nothing is selected on the items page then an error appears or the user is returned to another page.
When submit is selected the form action sends it to the confirm page and the below is executed which displays the items selected if there is 1 or more entered if ($partno == $varname & $qty > 0) but I dont no what to put in the else part to return an error or take the user back to the previous page.
<?php
$visitor = $_POST['visitor'];
echo "<p>" . 'Hello ' . "<b>" . $visitor . "</b> " . 'please confirm your purchase(s) below.' . "</p>";
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$total = 0;
foreach ($_POST as $varname => $varvalue) {
$qty = $varvalue;
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname & $qty > 0) {
echo "<tr><td><img src='$image' width='50' height='50' alt='image'</td>
<td>$partno<input type='hidden' name='$partno' value=$partno></td><td>$name</td><td>£$price</td>
<td> $qty</td><td><input type='hidden' name='visitor' value=$visitor></td>
<td><input type='hidden' name='qty' value=$qty></td></tr>";
$total = $total + $price * $qty;
} else {
}
}
}
?>
You'd have something like this:
$errors = array();
foreach(...) {
if ($partno == $varname & $qty > 0) {
... code for "ok" stuff
} else {
$errors[] = "$partno is incorrect";
}
}
if (count($errors) > 0) {
die("Errors: " . implode($errors));
}
... proceed to "success" code ...
Basically, for every test that fails, you record a message. Once the loop exits, if there's any error messages, you display them and abort processing. If there's no errors, you proceed onwards with the rest of the code.
Why not use a try catch block?
try {
if (isset($_POST)) {
if (!$email) {
throw new Exception('email is not valid', 100);
}
// everything is good process the request
}
throw new Exception('Error!', 200);
} catch (Exception $e) {
if ($e->getCode == 200) {
// redirect
} else {
// do something else
}
}
throw an Exception in your If statement, then put your data in try/catch block, so it will catch an exception if error occured
Consider the following approach: both the form and the php code to do something with the form data are on the same page. If the form was posted, you'll first check if the form was ok, after that you'll do something with the submitted data. If the form was not valid, display an error message.
The advantage is: no die() in the middle of your code, no strange redirects, everything in one script.
// simplified code in example.php
<?php
// in this variable we'll save success/error messages to print it
$msg = "";
// run this php code if the form was submitted
if(isset($_POST['submit'])) {
// is the form valid?
if (strlen($_POST['username']) == 0) {
$msg = "Please enter a username";
}
else {
// all validation tests are passed, give the user a nice feedback
// do something with the data, e.g. save it to the db
$msg = "Your data was saved. Have a great day";
}
}
?>
<div class="msg"><?php print $msg; ?></div>
<form method="post">
<input type="text" name="username">
<input type="submit" name="submit" value="Submit">
</form>
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' );`
}
I cannot get my PHP script to echo the second else statement if the first result empty.
The way my script currently works is "Print Addresses (from another array) > List Comments", however even if a comment is empty for an address is will either print the comments or nothing, I cannot make the script echo the word "No comment".
if(!empty($row['id']))
{
echo "$row[comment]<br/>";
}
else
{
echo "no comment<br/>";
}
Any help appreciated. Thanks.
Assuming this comes from a database and each row has an id, this will always be true:
if(!empty($row['id']))
Try:
if(!empty($row['comment']))
If id is something else, the same logic applies: check the value that you intend to print:
if (!empty($row['id']) && !empty($row['comment']))
{
echo $row['comment'].'<br/>';
}
else
{
echo "no comment<br/>";
}
EDIT: If this code is looping through all comments attached to a post or something, there will never be any output if there are no comments to loop through. In that case try something like this:
if (count($comments) === 0)
{
echo "no comments<br />";
}
else
{
foreach ($comments as $row)
{
if (!empty($row['comment']))
{
echo $row['comment'].'<br />';
}
else
{
echo "no comment<br />";
}
}
}
OR:
$comment_count = 0;
foreach ($comments as $row)
{
if (!empty($row['comment']))
{
echo $row['comment'].'<br />';
$comment_count++; // We have at least one comment
}
else
{
echo "no comment<br />";
}
}
if ($comment_count === 0) echo 'no comments<br />';
I know that it's not possible to style any given PHP but I do know that it is possible to style the output HTML that the PHP provides you with. I was wondering if there was any method available for me to use that would enable me to style the output from my IF ELSE statement.
if ($result != false) {
print "Your entry has successfully been entered into the blog.";
}
Just use HTML in your printed string. Nothing fancy needed.
if ($result != false) {
print "<p class=\"success\">Your <strong>entry</strong> has successfully been entered into the blog. <img src=\"smileyface.png\" alt=\"Smiley face\" /></p>";
}
You mean this?
if ($result != false) {
print "<span style='color:#ff0000'>Your entry has successfully been entered into the blog.</span>";
}
What I like to do, just to make life simple, is to switch between HTML and PHP in my page. For example,
<?php if ($fooSuccess = true) {?>
<p><span style="color: green;">Success!</span></p>
<?php } else {?>
<p><span style="color: red;">Error!</span></p>
<?php } ?>
You need to print HTML then.
if ($result != false) {
print "<b>Your entry has successfully been entered into the blog.</b>";
}
Or even
if ($result != false) {
print "<div class='Style1'>Your entry has successfully been entered into the blog.</div>";
}