I have a project where I need to enhance a given website. In the login page i have two fields (Username & password) and would like to display an error message in a pop up window if the user inputs wrong credentials.Was Thinking to do this in javascript The code i have till now is :
if (isset($errors) && !empty($errors)) {
echo '<p id="err_msg">Oops! There was a problem:<br>';
foreach ($errors as $msg) {
echo " - $msg<br>";
}
echo 'Please try again or Register</p>' ;
}
You don't need javascript for this. If you do the validation server side then you can guarantee the content is whats expected. You could use something like the following. Then set a timeout to hide the box if required.
<?php
$sError = '';
$sEmail = '';
// if email posted check/validate
if(isset($_POST['Email']) && $_POST['Email'] != ''){
if(valid_email($_POST['Email'])){
$sEmail = $_POST['Email'];
}else{
$sError .= "[InvalidEmail]";
}
}
// if email is blank after validation, add to error string
if($sEmail == '') $sError .= "[Email]";
// then print using php
if($sError !== ''){
if( strpos($sError, '[Email]') !== false ||
strpos($sError, '[Password]' ) !== false
){
echo"<div class=\"statusMessage alert alert-danger\" role=\"alert\"><ul>";
if(strpos($sError, '[Email]') !== false){
echo "<li>Please enter an email address</li>";
}
if(strpos($sError, '[InvalidEmail]') !== false){
echo "<li>Email provided is invalid</li>";
}
echo "</ul></div>";
}
}
?>
Related
if ($row['email'] == $email && $row['password'] == $password) {
echo "Login success Welcome".$row['username']; # code...
}
else{
echo "failed to login";
}
You can check if(!is_null($row)) along with the other checks, or simply:
if( $row && $row['email']==$email && $row['password']==$password ) { ... };
This happens when you query your DB, and there is no match, so there's no result, so the result is empty/null.. which you seem not to be checking within your code..
I was making a form for inserting products for admin in an e-commerce project. During validation of the form data, I tried to check if the form data is empty or not.
Thus I introduced an if statement and checked the values of all the parameters passed from the form and in the if block wrote an echo statement.
Here is my code:
<? php
//text variables
if(isset($_POST['insert_product'])){
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_brand = $_POST['product_brand'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_status = 'on';
$product_keywords = $_POST['product_keywords'];
//images variables
$product_img1 = $FILES['product_img1']['name'];
$product_img2 = $FILES['product_img2']['name'];
$product_img3 = $FILES['product_img3']['name'];
//temp names
$temp_name1 = $FILES['product_img1']['tmp_name'];
$temp_name2 = $FILES['product_img2']['tmp_name'];
$temp_name3 = $FILES['product_img3']['tmp_name'];
//validation and insertion query
if($product_title == '' OR $product_cat == '' OR $product_brand == '' OR $product_keywords == '' OR $product_img1 == '' OR $product_price == ''){
echo"<script>alert('you have not entered all the values')</script>";
exit();
}
}
?>
It is producing an output like
(...alert('you have not entered all the values');"; exit();} } ....)
Please help me to solve this problem.
I am using Sublime text and checked the same in Notepad++ but it’s giving the same error.
This works fine for me. Try iterating through $_POST in a loop, checking values that way. It'll condense your code and make things easier to read in the future:
<?php
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
if (!isset($_POST[$key]) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
}
}
That said, you should try to preserve $_POST and use a cleaned string if you're using data provided by the user:
<?php
if (isset($_POST)) {
// Clean a string, making it safe for using with a database.
function clean_string($string) {
global $mysqli;
$string = $mysqli->real_escape_string($string);
stripslashes($string);
return $string;
}
foreach ($_POST as $key => $value) {
if (!isset($_POST) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
// If you're going to be using this $_POST data with a database you should also
// clean the strings before using them in any way.
$Data = new stdClass();
foreach ($_POST as $key => $value) {
if (isset($_POST[$key]) && $_POST[$key] !== "") {
$Data->$key = clean_string($value);
}
}
}
// All of the $_POSTed items are set and cleaned for use. Do what you will with them below.
}
try the following, *note semicolon
echo "<script language='javascript'>alert('thanks!');</script>";
echo"<script>alert('you have not entered all the values');</script>";
use this .....u r forgetting semicon after )
I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>
the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.
I've tested my site's mailing with a different script - just to make sure it wasn't the host, and it's working fine.
I'm not sure why my code isn't working. I've included all my contact forums code except the html. It seems to not be loading the php, as it doesn't show any error messages when I put in an invalid email etc. - it just refreshes the page it seems.
Help is much appreciated, thanks everyone.
<!-- Contact Form Js -->
<script type="text/javascript">
// contact form js
jQuery(document).ready(function($) {
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "inc/contact-process.php",
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
setTimeout("location.reload(true);",7000);
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
});
</script>
<!-- End Contact -->
PHP - 'contact-processes'
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include dirname(dirname(__FILE__)).'/config.php';
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
if(!$error)
{
ini_set("sendmail_from", WEBMASTER_EMAIL); // for windows server
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
PHP - 'functions'
<?php
function ValidateEmail($value)
{
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($value == '') {
return false;
} else {
$string = preg_replace($regex, '', $value);
}
return empty($string) ? true : false;
}
?>
PHP - 'config'
<?php
define("WEBMASTER_EMAIL", 'snip#myemail.com');
?>
I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});