call a php function inside a div - php

I want to make a call of this php logic inside a html div but when passing it as a function the logic breaks since it does not send an error message in case of entering the pass wrong and its confirmation at the time of performing the password change.
<?php
require 'funcs/conexion.php';
require 'funcs/funcs.php';
$user_id = $mysqli->real_escape_string($_POST['user_id']);
$token = $mysqli->real_escape_string($_POST['token']);
$password = $mysqli->real_escape_string($_POST['password']);
$con_password = $mysqli->real_escape_string($_POST['con_password']);
if(validaPassword($password, $con_password))
{
$pass_hash = hashPassword($password);
if(cambiaPassword($pass_hash, $user_id, $token))
{
echo "Contraseña Modificada <br> <a href='index_alumnos.php' >Iniciar Sesion</a>";
} else {
echo "Error al modificar contraseña";
}
} else {
echo "Las contraseñas no coinciden <br> <a href='index_alumnos.php' >contacta a Academia</a>";
}
?>

If the echo happens before your actual div is drawn, the echo goes... right where it happens. Which isn't within your div.
One way of getting around this would be to put your error message into a variable and then deliver this variable into your div (whether it be through a return value, if it's a call, or some other means.)
Here's a simple example to illustrate this:
<?php
if(1 === 2) {
//great, 1 is 2
} else {
//oh no, an error
$someErrorLine = '1 is not 2';
} ?>
<h1>Hi</h1>
<div><?= $someErrorLine ?></div>
You could also check if the variable exists, something like if(isset($someErrorLine)) {} and echo the div with it, or put the div within your variable.

Related

Setting General Messages Using Flash Message

I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>

Pass multiple values through header function

I want to set a message for the user to see in php, but I'm having issues crossing controllers. Here was my first try:
if($revOutcome > 0){
$message = "<p>Review updated!</p>";
header('Location: /acme/accounts/index.php?action=seshLink');
exit;
}
And here was my second try:
if($revOutcome > 0){
header('Location: /acme/accounts/index.php?action=seshLink&message=Update was successful!');
exit;
}
I have an isset in the view that checks if $message is set, and if it is, echo what is displayed in $message. But for some reason, it's not displaying. Here is the code for the view:
<?php
if (isset($message)) {
echo $message;
}
?>
And here is the switch case statement seshLink:
case 'seshLink':
$userId = $clientData['clientId'];
$revData = getCliRev($userId);
if(!$revData){
$message = "<p>No reviews here yet. Write your first one today!</p>";
include '../view/admin.php';
exit;
}
else {
$RevDisplay = buildAdminReviewDisplay($revData);
}
include '../view/admin.php';
break;
I really don't know why $message isn't displaying.
Because you are making a request call (parameters through url) which means that you need to get your variables using $_GET array like
...
if (isset($_GET["message"]))
...

Send a POST value only with PHP

I want to use my webpage to recognize if a $_POST is set and the, if it is, print it in the page, so this is what I really have now:
if (isset($_POST['error'])) {
echo '<div id="error">'.$_POST['error'].'</div>';
}
But what I want is that, when an if statement that I have in the same document returns true, to send a POST request to that same file and so, show the error message with the $_POST. Is this possible or it is another easy way for doing it?
Sorry for not explaining so well, this is my code:
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
// Set the $_POST['error'] to an error message so I can show it in the error DIV.
}
Thanks!
You can define a $message athe beginning of your page then handle the errors you want to show
$message = '';
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
//set a proper message ID which will be handled in your DIV
$message_id = 1;
header('location: /current_path.php?message='.$message_id);
}
Now in the div you can show it as
if (!empty($_GET['message'])) {
echo '<div id="error">';
if ($_GET['message'] == 1) { echo 'First message to show.'; }
elseif ($_GET['message'] == 2) { echo 'Second message to show.'; }
echo '</div>';
}

Variable doesn't get defined/updated after function processes?

I have coded some alerting system.
But let's not look at the system itself, Let's look at how will the system know that the system really did sent the alert/error to the browsing user.
I have made something so when you randomly go to ?alert=name, without doing any error, it will say 'No errors'.
But if the system makes you go to ?alert=name, it will echo the error.
How I handle posts
function postComment() {
if (!empty($_POST['name']) || !empty($_POST['comment'])) {
$comment = mysql_real_escape_string(htmlentities($_POST['comment']));
$guest = mysql_real_escape_string(htmlentities($_POST['name']));
}
$guestId = 1;
if (empty($guest)) {
$alert = 1;
return header('location: index.php?alert=name');
}
if (empty($comment)) {
$alert = 2;
return header('location: index.php?alert=comment');
}
if (!isset($_COOKIE['alreadyPosted'])) {
mysql_query("INSERT INTO `comments` (`comment_guest`, `guest_id`, `comment`, `comment_date`, `comment_time`) VALUES ('$guest', '$guestId', '$comment', CURDATE(), CURTIME())") or die(mysql_error());
header('Location: index.php?action=sucess');
setcookie(alreadyPosted, $cookieId+1, time() + 60);
} else {
$alert = 3;
header('location: index.php?alert=delay');
}
}
As you see, to check if user really getting that error, I will set $alert to whatever error number it is.
And to check if hes getting the error I will use this:
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
You will probably wonder why I am doing it this way.., well because I use 1 function for post, and my post function goes under the form, and i want the alerts to display up to the form.
Problem:
The variable either doesn't get set to the number that it is supposed to when running the function,
or.. something is blocking it from it.. I don't know..
My guess: Because the check for errors is located up to the postComment function before the variables even get set?
<?php
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
?>
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="Your name here" class="field">
<textarea class="textarea" name="comment" placeholder="Your comment here..."></textarea>
<input type="submit" name="send" class="blue_button" value="Post Comment">
</form><input type="submit" name="" id="margin" class="blue_button" value="See all messages">
<br />
<?php
//Show the comments
showComments();
if (isset($_POST['send'])) {
postComment();
}
if (isset($_GET['delete']) == "comment"){
deleteComment();
}
echo '<br />';
?>
If it is, what is the solution?
Thanks!
Please don't start with the story about mysql_ function, I understood & I will use PDO instead, but I am using mysql_ at the moment for testing purposes
The problem is that you're redirecting on an error, and so the $alert variable does not get carried over.
To fix the problem add the alert type to the $_GET parameters:
function postComment()
{
// ...
if (empty($guest))
{
header('location: index.php?alert=name&alert_type=1');
exit;
}
// ...
}
And then when you check for the error:
if (isset($_GET['alert']) && 'name' == $_GET['alert'])
{
if (isset($_GET['alert_type']) && '1' == $_GET['alert_type'])
{
echo 'hai';
}
else
{
echo 'No errors';
}
}
Note also that I fixed the error here:
isset($_GET['alert']) == 'name'
That doesn't do what I think you think it does. What you want is:
isset($_GET['alert']) && 'name' == $_GET['alert']
(Excuse the order of the comparison; I prefer to have variables on the right for comparisons as it will cause a parse error if you miss a = -- much better than having it run but not do what you expect)
if you are a newbie, you better consider using client side scripting (viz javascript) for validation as using server side validation will simple make the process longer. but as you are facing problems, this might give you the solution.
as you are redirecting the page to index.php?alert=name', so $alert is never set initially when the page loads itself. when you call the function postcomment(), $alert is initiated but immediately destroyed when the system redirects. And as $alert never holds a value when you randomly visit the page, it shows no error.

[PHP / AJAX]: Change color of the message according to the entered text

In my website home page, I have a new user registration Form. It contains a field "User Name". When the user enters the user name and the focus is pointed to another field, an AJAX code is executed that checks whether any user with the entered username already exists or not.
The AJAX code that I am using is this:
function toggle_username(userid) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
handle = document.getElementById(userid);
var url = 'ajax.php?';
if(handle.value.length > 0) {
var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value);
http.open("GET", fullurl, true);
http.send(null);
http.onreadystatechange = statechange_username;
}
else
{
document.getElementById('username_exists').innerHTML = '';
}
}
The file "AJAX.PHP" called by the above code, is like this:
<?php
mysql_connect ('localhost', 'MyServer', 'user1');
mysql_select_db('globaldb');
$do = $_GET['do'];
switch($do) {
case 'check_username_exists':
if(get_magic_quotes_gpc()) {
$username = $_GET['username'];
}else{
$username = addslashes($_GET['username']);
}
$count = mysql_num_rows(mysql_query("SELECT * FROM `student_login` WHERE `username`='".$username."'"));
header('Content-Type: text/xml');
header('Pragma: no-cache');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<result>';
if($count > 0) {
$_SESSION['UserExists'] = "true";
}else{
$_SESSION['UserExists'] = "false";
}
$_SESSION['UserExists'] = "false";
echo '</result>';
break;
default:
echo 'Error, invalid action';
break;
}
?>
In my registration form, just below the username input box, I want to define a section where in I can show the messages:
User with this name exists, or
Username is available.
In my home page, I am using following code:
<input name="username" type="text" id="username" onchange="toggle_username('username')" style="width:150px;" maxlength="40" size="22" >
<?PHP
if ($_SESSION['UserExists'] == "true")
{
echo "<div id='username_exists' style='font-size: 11px;font-weight: bold;color:red'>User with this name unavailable.</div>";
}
else
{
echo "<div id='username_exists' style='font-size: 11px;font-weight: bold;color:darkgreen'> User with this name is available </div>";
}
?>
The home page consists of the above code and the first code block (JavaScript) on top that I gave.
This code is not working. And I guess the reason is that I am have included the messages in the PHP block. Being server-side, it is not showing the messages.
Please let me know how to handle this issue. Whether to modify the JavaScript code that calls the AJAX or include something in the PHP.
Please also note that what actually I want is to show the messages in green or red color. If the user name is available, then green else in red color.
I'd do this using jQuery and have the PHP page return a code (0 for false, 1 for true) or similar. You can then use jQuery's addClass() method depending on the returned result, all in the javascript.
How about having ajax.php return a bit of pre-formatted HTML and using the statechange_username function, which you've set to process the response, to stick it in a placeholder div/span?
By the way, why are you setting a session variable?
I guess you are missing the statechange_username function, something like
function statechange_username()
{
if (http.readyState==4)
{
document.getElementById(\"username_eixsts\").innerHTML=http.responseText;
}
}

Categories