The title may seem a bit confusing, but let me just tell you what I am trying to do. So I have a registration form in register.php. The form data is processed by my register.class.php file on a keyup by the user, and any errors in the submitted data are then returned and put into a "#return" div (in register.php).
The "#return_error" is echoing just fine, I'm having no problems echoing that, but for some reason, even if there are no errors, the "#return_success" won't echo.
I'm fairly new to jQuery, so please forgive me.
Here are the files:
register.class.php
//this is just an excerpt from the file, the rest of the code in the file was just validation.
$register = new Register();
$username = $_POST['username'];
$email1 = $_POST['email'];
$email2 = $_POST['reemail'];
$pass1 = $_POST['pass'];
$pass2 = $_POST['repass'];
$register->Username($username, $mysqli);
$register->Email($email1, $email2, $mysqli);
$register->Password($pass1, $pass2);
// no errors are found
if ($register->getStatus() === true) {
echo "<div id=\"return_success\">";
echo "<ul>";
echo "<li><b>Everything is valid</b></li>";
echo "</ul>";
echo "</div>";
} else {
//errors found
echo "<div id=\"return_error\">";
echo "<ul>";
foreach ($register->errors as $error) {
echo "<li><b>" . $error . "</b></li>";
}
echo "</ul>";
echo "</div>";
}
script.js
$(document).ready(function() {
$("#return").hide();
$("#register input").keyup(function() {
$.post("classes/register.class.php", $("#register").serialize(), function(data) {
$("#return").html(data);
$("#return").show();
if (data === '') {
$("#return").hide();
}
});
});
});
Related
I has read all the various post on StackOverflow regards this same but that was not helpful ...
Php script not shows error alert when text box empty or in invalid pattern. I know only empty script which I mention below but I don't known How I add pattern error also.
Also when textbox empty it not show error why? Please help. Please don't mark as it is duplicate because I read various post but same issue that is why I posted a threads. Please help in full script.
Advance thank you..
<?php
if(isset($_POST['submit']))
{
$name= $_POST['name'];
if (!($name))
{
$m1 = "<Div class="alert">Enter your Name</Div>" ;
}
$email= $_POST['email'];
if (!($email))
{
$m2 = "<Div class="alert">Enter Your Email"</Div> ;
}
$_SESSION['name'] =$name;
$_SESSION['email'] =$email;
$_SESSION['otp']=$rndno;
header( "Location: next-page.php" );
}
?>
In HTML Body
<div>
<?php if(isset($m1)) { echo $m1; } ?>
<?php if(isset($m2)) { echo $m2; } ?>
</div>
Try This code it is runnable
<?php
if(isset($_POST['submit']))
{
$name= $_POST['name'];
if ( $name == '')
{
echo $m1 = "<script type='text/javascript'>alert('Please Enter Your Name');</script>" ;
}
$email= $_POST['email'];
elseif ( $email == '')
{
echo $m2 = "<script type='text/javascript'>alert('Enter Your E-mail');</script>" ;
}
$_SESSION['name'] =$name;
$_SESSION['email'] =$email;
$_SESSION['otp']=$rndno;
else{
header( "Location: next-page.php" );
}
}
?>
Ok, so when I execute the initial function it works fine, the username gets stored in the database, however when I run the second function that appends the username to the text the user chooses to enter the IF statement returns 'no user' - when a user is defined...
If anyone knows how to fix this that would be great - I am currently learning PHP and mysql so I am sorry if any of this is incorrect
<?php
session_start()
// connect to the database
mysql_connect("localhost", "root", "");
mysql_select_db("ajaxchat");
// read the stage
$stage = $_POST['stage'];
// primary code
if($stage == 'initial') {
// check the username
$user = $_POST['user'];
$query = mysql_query("SELECT * FROM chat_active WHERE user='$user'");
if (mysql_num_rows($query) == 0) {
$time = time();
//
mysql_query("INSERT INTO chat_active VALUES ('$user', '$time')");
// set the session
$_SESSION['user'] = $user;
echo 'good';
}
else {
echo 'taken';
}
}
/////////////// PROBLEM FUNCTION ///////////////
================================================
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
// check for user_error
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
}
}
else {
echo 'error';
}
?>
This is the javascript:
<script type="text/javascript">
function chat_initialise() {
var user = document.getElementById("chat_user").value;
$.post("./chat.php", {stage:"initial", user:user}, function(data) {
if (data == "good") {
$('#initial').css('display', 'none');
$('#content').css('display', 'inline')
}
else {
alert("That username is taken! Please try another.");
}
});
}
function chat_send() {
var text = document.getElementById("chat_text").value;
$.post("./chat.php", {stage:"send", text:text}, function(data) {
document.getElementById("chat_text").value = '';
$('#window').text($('#window').text() + data);
// alert(data)
});
}
</script>
I fixed it - changed the POST function to take the current username then redefine it as a variable in the second function:
else if($stage == 'send') {
// get the textdomain
$text = $_POST['text'];
$user = $_POST['user'];
echo $user;
// check for user_error
if (isset($_SESSION['user'])) {
$_SESSION['user'] = $user;
echo $user.' - '.$text.'<br />';
}
else {
echo 'no user';
var_dump($_SESSION);
}
}
Thanks for all your help guys!!
I'm very new to php. I found some CMS like code for east text editing here on SO and now I'm trying to implement it on our micro site.
My problem is, that I want login error report to show on exact position on the page - just under the login button.
Can someone tell me how can I put that error report text whereever I want? I don't want to override it with CSS positioning.
In basic, I want to put that p class="error":
<?php
if (empty($_POST) && isset($_GET['action'])) {
$action = $_GET['action'];
switch ($action) {
case 'logout':
session_unset();
session_destroy();
break;
}
}
if (!isset($_SESSION['user'])) {
$user = '';
$pass = '';
if (isset($_POST['login'])) {
$user = strtolower(trim($_POST['user']));
$pass = $_POST['pass'];
$errors = array();
if ($user == '' || $user != '1') {
$errors['user'] = '';
}
if ($pass == '' || $pass != '1') {
$errors['pass'] = '';
}
if (empty($errors)) {
$_SESSION['user'] = $user;
} else {
echo '<p class="error">Insert correct ';
if (isset($errors['user']))
echo 'name';
if (count($errors) == 2)
echo ' a ';
if (isset($errors['pass']))
echo 'password';
echo '.</p>', "\n";
}
}
}
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
?>
somewhere else in the whole code of my page. Do I need to cut out something from that php code, or do I need to write new part of code for that?
Thank you for you help, Matej
Instead of just doing 'echo' all over the place, which means you get output at the place where the PHP code is embedded in the page, set some flags/message variables to output later.
e.g.
<?php
$errors = false;
$msgs = '';
if (....) {
$errors = true;
$msgs = "something dun gone wrong";
}
?>
... various bits of your html go here ...
<?php if ($errors) { echo $msgs; } ?>
... more html here ...
I've created a test form that uses IF.. ELSE to validate data in a simple form. This works ok and any validation messages or errors are posted to the same page (userform.php) to inform the user of success or otherwise.
What I want to do now is take the user to a different page on successful completion of the form. Here's my code so far:
<?php
if (isset($_POST['email'], $_POST['password'])) {
$errors = array ();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form";
}
if (empty($email)) {
$errors [] = "You must enter an email address";
}
if (empty($password)) {
$errors [] = "You must enter a password";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
}
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
$result = "userform.php";
}
} else {
$result = "confirm.php";
}
?>
<form action="<?php echo $result ?>" method="post">
The idea is that the users success or otherwise in completing the form changes the $result variable which is used in the form action. The above code doesn't work, so how would I do it?
Is it even possible?
instead of "form action=" at the bottom:
<?php
include($result);
?>
As I understand it you want it to work like so:
User fills form
User submits form
Form submission goes to userform.php
If all values validate, continue to confirm.php
If not, return to userform.php
If that's the case, I don't think you want to change the form action: that would require that the user re-submit the form. Instead, use a HTTP redirect to send them to confirm.php:
header("Location: confirm.php");
... or if you wanna be really by-the-book about it:
header("Status: 303 See Other");
header("Location: http://exampel.com/confirm.php"); // according to the protocol,
// `Location` headers should be full URLs
<?php
/* ... */
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
}
?>
<form action="userform.php" method="post">
<?php
} else {
header("Location: confirm.php");
// if you need to pass additional information to confirm.php, use a query string:
// header("Location: confirm.php?var1=".$var1);
}
?>
The way you're doing it now, will redirect the user to confirm.php if they submit the form for a second time. You could change your code to this:
} else {
// $result = "confirm.php";
header("Location: confirm.php");
exit();
}
That way, if everything has been entered, the user will be redirected to confirm.php. But what do you do with the variables if everything is allright? They won't be taken to the new page.
} else {
$result = confirm.php;
foreach($_POST as $key => $val){
$input.="<input type='hidden' name='$key' value='$val' />";
}
$form = "<form method='post' name='confirm' action='confirm.php'>".$input."</form>";
$script = "<script type='text/javascript'>document.confirm.submit();</script>";
echo $form.$script;
}
empty ($errors)
will ALWAYS return empty. That's why you always get:
$result = 'confirm.php';
Check return values here
Also, I don't think you can do this easily. Instead, why don't you just create a check.php or whatever to check the variables/check for errors, etc. Then do whatever you want (redirect back to the form-filling page or proceeding to confirm.php page.
The whole idea is wrong. You have to fix 2 issues in your code.
1. A major one. Learn to properly indent nested code blocks!
It's impossible to read such an ugly mass with no indents.
2. A minor one.
I see no use of confirmation page here. What are you gonna do on that page? And from where you're going to get form values?
It seems you have to either use just simple Javascript code to show a confirmation or store entered data into session
And, I have to say, that show a confirmation page for simply a feedback form is quite uncommon practice.
So, I think you really need only one form action and only thing to ccare is properly filled form
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$errors = array();
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form. All fields required.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
if (!$errors) {
// do whatever you wish to this data
// and then redirect to whatever address again
// the current one is a default
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['fiestname'] = $form['lasttname'] = $form['email'] = $form['password'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($errors): ?>
<? foreach($errors as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form method="POST">
<input type="text" name="firstname" value=<?=$form['firstname']>
... and so on
I have a form with several input fields, i would like to go through and check to make sure they are all present before continuing.
This is the code i am using
if(isset($_POST['url'])){ $url = $_POST['url']; } else { echo "<error>no url</error></data></xml>"; exit(); }
if(isset($_POST['username'])){ $username = $_POST['username']; } else { echo "<error>no username</error></data></xml>"; exit(); }
if(isset($_POST['password'])){ $password = $_POST['password']; } else { echo "<error>no password</error></data></xml>"; exit(); }
if(isset($_POST['cachename'])){ $cachename = $_POST['cachename']; } else { echo "<error>no cachename</error></data></xml>"; exit(); }
if(isset($_POST['lat'])){ $lat = $_POST['lat']; } else { echo "<error>no lat</error></data></xml>"; exit(); }
if(isset($_POST['long'])){ $long = $_POST['long']; } else { echo "<error>no long</error></data></xml>"; exit(); }
if(isset($_POST['message'])){ $message = $_POST['message']; } else { echo "<error>no message</error></data></xml>"; exit(); }
if(isset($_POST['notes'])){ $notes = $_POST['notes']; } else { echo "<error>no notes</error></data></xml>"; exit(); }
if(isset($_POST['tags'])){ $tags = $_POST['tags']; } else { echo "<error>no tags</error></data></xml>"; exit(); }
The problem im getting, is even when i JUST enter a URL, it returns "no lat". Even when i fill in everything down to notes, it still returns "no lat"
Any ideas?
Check values in $_POST
echo "<pre>";
print_r($_POST);
echo "</pre>";
Make sure every post variable is set and the names match.
Not that this will fix your problem (see Ólafur's comment), but, here's a more automated way of performing validation on all of your fields:
$required = array('url', 'username', 'password', 'cachename',
'lat', 'long', 'message', 'notes', 'tags');
while (list($i, $require)=each($required)){
if(empty($_POST[$require])){
die('<error>no ' . $require . '</error></data></xml>');
}else{
$$require = $_POST[$require];
}
}
PS: empty() is often better better to use than isset(). An empty string will return true with the isset() function.