Not sure why, but I added an "error" clause to make sure the AJAX was failing... it is. It works correctly up to the AJAX portion, it's just not sending the data, no idea why.
<script type="text/javascript">
<!--
$(document).ready(function() {
$("#login").click(function() {
document.getElementById("result").innerHTML = 'Validating credentials...';
var un = $("#un").val();
var pw = $("#pw").val();
if ( un == "" )
{
document.getElementById("un_error").style.visibility = 'visible';
$("#un").focus();
}
if ( pw == "" )
{
document.getElementById("pw_error").style.visibility = 'visible';
$("#pw").focus();
}
$.ajax({
type: 'POST',
url: 'login-parse.php',
data: { un: un, pw: md5(pw) },
success: function(msg) {
document.getElementById("result").innerHTML = msg;
},
error: function(xhr, status) { alert(status); }
});
});
});
//-->
</script>
That's the JS code.
This is the HTML:
<div id="content">
<div id="result" class="result"></div>
<h2>Login To Your Account</h2>
<div class="text">
<fieldset>
<fieldset>
<legend>Username</legend>
<input type="text" id="un" value="" size="20" /><span class="error" id="un_error">*</span>
</fieldset>
<fieldset>
<legend>Password</legend>
<input type="password" id="pw" value="" size="30" /> <span class="error" id="pw_error">*</span>
</fieldset>
<input type="button" id="login" value="Login" />
</fieldset>
</div>
</div>
<?php
// Login Parser
require 'inc.common.php';
if (! isset ( $_POST['un'], $_POST['pw']) )
{
echo '<blockquote>Invalid username/password combination.</blockquote>' . "\n";
} else {
$un = $_POST['un'];
$pw = md5($_POST['pw']);
$check = $sql->result ( $sql->query ( 'SELECT COUNT(*) FROM `users` WHERE `user_name` = \'' . $sql->escape($un) . '\' AND `user_password` = \'' . $sql->escape($pw) . '\'' ) );
$errors = array();
if (! strlen ( $un ) )
$errors[] = 'Please enter a valid username.';
if (! strlen ( $pw ) )
$errors[] = 'Please enter a valid password.';
if ( $check == 0 )
$errors[] = 'Invalid username/password combination.';
if ( count ( $errors ) > 0 )
{
echo '<blockquote>' . "\n",
' The following errors occurred with your login:' . "\n",
' <ul>' . "\n";
foreach ( $errors as $enum => $error )
{
echo ' <li><strong>(#' . ($enum+1) . '):</strong> ' . $error . '</li>' . "\n";
}
echo ' </ul>' . "\n",
'</blockquote>' . "\n";
} else {
setcookie ( 'ajax_un', $un, time()+60*3600 );
setcookie ( 'ajax_pw', $pw, time()+60*3600 );
echo '<blockquote>' . "\n",
' <p><strong>Success!</strong></p>' . "\n",
' <p>You have successfully been logged in as <strong>' . $un . '</strong>.</p>' . "\n",
' <p>You may now return to the index page.</p>' . "\n",
'</blockquote>' . "\n";
}
}
?>
From the message "500 - Internal Server Error" in Firebug console, and the code you have posted, it seems that there is some problem in database operation.
So try to store your query a variable. Echo it and try executing same in phpMyadmin or other equivalent client you are using to access database.
If possible also post the result.
Related
I am not able to post data to MySql database. I am running the project on chrome browser(windows7). Here I can see the params but they are not sent to the database table. What actually is the problem with my code?
My php code is:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysqli_connect("localhost","root",'') or die ("Could not connect: " . mysql_error());;
mysqli_select_db($con, 'db_lastLog');
$qry_em = 'select count(*) as cnt from users where email ="' . $email . '"';
$qry_res = mysqli_query($con, $qry_em);
$res = mysqli_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,pass,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysqli_query($con, $qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
My controller code is:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function (userdata) {
var request = $http({
method: "POST",
url: "http://localhost/lastLog.php",
crossDomain : true,
data: {
username : userdata.username,
password : userdata.password,
email : userdata.email
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Successfully Created Account";
}
if(data == "2"){
$scope.responseMessage = "Cannot Create Account";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exist"
}
});
}
})
My html code is:
<ion-pane>
<ion-header-bar class="bar-positive">
<h2 class="title">SignUp</h2>
</ion-header-bar>
<ion-view view-title="SignUp" name="signup-view">
<ion-content class="has-header" ng-controller="SignupCtrl">
<div class="list list-inset">
<label class="item item-input">
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input">
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input">
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-positive" ng-click="signup(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
</ion-pane>
Trying to work out the best way to get the PHP below to post to a different user email address dependent on the form name it is coming from.
Eg. this form is name="engineering-australia" and I have others with different names. I want this one to go to user1#domain.com and an other to go to user2#domain.com and so on.
My question is, what would be the best way to do this, I don't want to use javascript- I was thinking some kind of if statement? But wouldn't the form name need to be pulled in somehow?
Also worth mentioning the forms are identical apart from the form name, I didn't want to just create a different PHP script for each form.
HTML
<form class="form-contact" name="engineering-australia">
<fieldset>
<input id="form-name" name="name" type="text" placeholder="Your Name" />
<input id="form-email" name="email" type="text" placeholder="Your Email" />
</fieldset>
<textarea id="form-msg" name="message" rows="10" placeholder="Your Message" ></textarea>
<input type="submit" name="submit" class="button button-small" value="Send Message" />
</form>
PHP
<?php
define('kOptional', true);
define('kMandatory', false);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('track_errors', true);
function DoStripSlashes($fieldValue) {
// temporary fix for PHP6 compatibility - magic quotes deprecated in PHP6
if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
if (is_array($fieldValue) ) {
return array_map('DoStripSlashes', $fieldValue);
} else {
return trim(stripslashes($fieldValue));
}
} else {
return $fieldValue;
}
}
function FilterCChars($theString) {
return preg_replace('/[\x00-\x1F]/', '', $theString);
}
function CheckEmail($email, $optional) {
if ( (strlen($email) == 0) && ($optional === kOptional) ) {
return true;
} elseif ( preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $email) == 1 ) {
return true;
} else {
return false;
}
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
$FTGname = DoStripSlashes( $_POST['name'] );
$FTGemail = DoStripSlashes( $_POST['email'] );
$FTGmessage = DoStripSlashes( $_POST['message'] );
$FTGsubmit = DoStripSlashes( $_POST['submit'] );
$validationFailed = false;
# Fields Validations
if (!CheckEmail($FTGemail, kMandatory)) {
$FTGErrorMessage['email'] = 'ERROR MESSAGE';
$validationFailed = true;
}
# Redirect user to error message
if ($validationFailed === true) {
header("Location: index.php?success=2");
}
if ( $validationFailed === false ) {
# Email to Form Owner
$emailSubject = FilterCChars("Website Enquiry");
$emailBody = chunk_split( base64_encode( "<html>\n"
. "<head>\n"
. "<title></title>\n"
. "</head>\n"
. "<body>\n"
. "Name : $FTGname<br />\n"
. "Email : $FTGemail<br />\n"
. "Message : " . nl2br( $FTGmessage ) . "\n"
. "</body>\n"
. "</html>" ) )
. "\n";
$emailTo = 'User <user1#domain.com>';
$emailFrom = FilterCChars("$FTGemail");
$emailHeader = "From: $emailFrom\n"
. "MIME-Version: 1.0\n"
. "Content-Type: text/html; charset=\"UTF-8\"\n"
. "Content-Transfer-Encoding: base64\n"
. "\n";
mail($emailTo, $emailSubject, $emailBody, $emailHeader);
# Redirect user to success message
header("Location: index.php?success=1");
}
?>
You're not going to get the form name in PHP. Try using a hidden input in each form:
<input name="form" type="hidden" value="engineering-australia" />
Then check $_POST['form'] in PHP.
switch($_POST['form']) {
case 'engineering-australia':
$email = 'user1#domain.com';
break;
case 'something-else':
$email = 'user2#domain.com';
break;
}
Change:
<form class="form-contact" name="engineering-australia">
<fieldset>
To:
<form class="form-contact">
<input type="hidden" name="post-to" value="engineering-australia" />
<fieldset>
Now you can check who you want to send the email to by simply requesting $_POST['post-to'] on the submit action page.
Based on this question i had to rewrite my contact form script.
The goal is to to have a send button labeled send. After clickick it should show sending till the php script is done. When its done it should show sent.
Thats my simple form:
<form id="contactForm" action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="Name" required><br />
<input type="text" id="email" name="email" placeholder="Mail" required><br />
<textarea name="message" id="message" placeholder="Nachricht" required></textarea><br />
<button name="submit" type="submit" id="submit">send</button>
</form>
Here is the jquery script for the label changing and the ajax submit.
<script>
$( init );
function init() {
$('#contactForm').submit( submitForm );
}
function submitForm() {
var contactForm = $(this);
if ( !$('#name').val() || !$('#email').val() || !$('#message').val() ) {
$('#submit').html('error');
} else {
$('#submit').html('sending');
$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
$('#submit').HTML = ('sent');
} else {
$('#submit').html('error');
}
}
</script>
the mail.php:
<?php
define( "RECIPIENT_NAME", "John Doe" );
define( "RECIPIENT_EMAIL", "john#doe.com" );
define( "EMAIL_SUBJECT", "Subject" );
$success = false;
$name = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "Von: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
//add html for javascript off user
}
?>
Its submits correct and i get the mail but i doesnt change the label to sent.Its stuck at sending.
Any idea or suggestions whats wrong with my code?
best regards
dennym
The error is on this line:
$('#submit').HTML = ('sent');
Change that to:
$('#submit').html('sent');
$('#submit').HTML = ('sent');
should be
$('#submit').html('sent');
like you have everywhere else.
You have to change
$('#submit').HTML = ('sent');
to:
$('#submit').html('sent');
in your function submitFinished();
I am creating a user settings page allowing members to update their information. The information displays, however once changed doesn't update on the database, although no errors are produced and the success page is displayed. I have tried echoing the array and it appears to be blank meaning it's not parsing any of the new data.
<?php
include ("storescripts/init.php");
protect_page();
if (empty($_POST) === false) {
$required_fields = array('mem_email','mem_first_name','mem_last_name');
foreach ($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) == true) {
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (empty($errors) === true) {
if (filter_var($_POST['mem_email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
} else if(user_exists($_POST['mem_email']) === 1 && $member_data['mem_email'] !== $_POST['mem_email']) {
$errors[] = 'Sorry, the email \'' . htmlentities($_POST['mem_email']) . '\' is already in use';
}
}
}
if (empty($_POST) === false && empty($errors) === true) {
$update_data = array(
'mem_first_name' => $_POST['mem_first_name'],
'mem_last_name' => $_POST['mem_last_name'],
'mem_email' => $_POST['mem_email'],
'allow_email' => ($_POST['allow_email']) ? 1 : 0);
update_user($session_member_id, $update_data);
header('Location: settings.php?success=1');
die();
}
include ("includes/overall/head.php");
?>
<?php include ("includes/overall/template_header.php");?>
<div id="mainDivShort">
<h1>User Settings</h1>
<div id="divBreak"></div>
<?php include ("includes/overall/column_left.php");?>
<div id="middleContent">
<?php if (isset($_GET['success']) && isset($_GET['success'])) {
echo 'Your details have been updated';
} else {
if (empty($errors) === false) {
echo output_errors($errors);
}?>
<form action="" method="post">
<ul>
<li>First Name*: <br> <input type="text" name="mem_first_name"
value="<?php echo $member_data['mem_first_name'];?>">
</li>
<li>Last Name*: <br> <input type="text" name="mem_last_name"
value="<?php echo $member_data['mem_last_name'];?>">
</li>
<li>Email*: <br> <input type="text" name="mem_email"
value="<?php echo $member_data['mem_email'];? >">
</li>
<li>
<input type="checkbox" name="allow_email" <? php if ($member_data['allow_email'] == 1) { echo 'checked="checked"'; } ?>> Would you like to receive an email about news and promotions?
</li>
<li><input type="submit" value="Update">
</li>
</ul>
</form>
<?php }?>
</div>
<?php include ("includes/overall/column_right.php");?>
</div>
<?php include ("includes/overall/template_footer.php");?>
And my update_user function
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id`= $mem_id");
}
do you receive the correct data in your update_user function ?
try this
function update_user($mem_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$sql = "UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id`= $mem_id";
echo $sql; exit();
//mysql_query("UPDATE `members` SET " . implode(', ', $update) . " WHERE `mem_id`= $mem_id");
}
Fire this $sql output in your db to check if you have sql errors or any other db errors
The funny thing is it did work for one evening. I contacted my host, and they are saying there's no reason it should not be working. I have also attempted to test it in Firebug, but it seemed to be sending. And I specifically put the email address (hosted in my domain) on my email safe list, so that is not the culprit either.
Would anyone here take a look at it for me? I'd be so grateful.
In the header I have:
<script type="text/javascript">
$(document).ready(function () {
var options = {
target: '#alert'
};
$('#contactForm').ajaxForm(options);
});
$.fn.clearForm = function () {
return this.each(function () {
var type = this.type,
tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
Here is the actual form:
<form id="contactForm" method="post" action="sendmail.php">
<fieldset>
<p>Email Me</p>
<div id="fieldset_container">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" /><br /><br />
<label for="email">Email:</label>
<input type="text" name="email" id="email" /><br /><br />
<span style="display:none;">
<label for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" />
</span><br /><br />
<label for="message">Comments & Inquiries:</label>
<textarea name="message" id="message" cols="" rows=""></textarea><br/>
</div>
<div id="submit_button">
<input type="submit" name="submit" id="submit" value="Send It" />
</div>
</fieldset>
</form>
<div class="message"><div id="alert"></div></div>
Here is the code from my validating page, sendmail.php:
<?php
// Who you want to recieve the emails from the form. (Hint: generally you.)
$sendto = 'my#emailaddress.com';
// The subject you'll see in your inbox
$subject = 'SH Contact Form';
// Message for the user when he/she doesn't fill in the form correctly.
$errormessage = 'There seems to have been a problem. May I suggest...';
// Message for the user when he/she fills in the form correctly.
$thanks = "Thanks for the email!";
// Message for the bot when it fills in in at all.
$honeypot = "You filled in the honeypot! If you're human, try again!";
// Various messages displayed when the fields are empty.
$emptyname = 'Entering your name?';
$emptyemail = 'Entering your email address?';
$emptymessage = 'Entering a message?';
// Various messages displayed when the fields are incorrectly formatted.
$alertname = 'Entering your name using only the standard alphabet?';
$alertemail = 'Entering your email in this format: <i>name#example.com</i>?';
$alertmessage = "Making sure you aren't using any parenthesis or other escaping characters in the message? Most URLS are fine though!";
//Setting used variables.
$alert = '';
$pass = 0;
// Sanitizing the data, kind of done via error messages first. Twice is better! ;-)
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
//The first if for honeypot.
if ( empty($_REQUEST['last']) ) {
// A bunch of if's for all the fields and the error messages.
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
} elseif ( ereg( "[][{}()*+?.\\^$|]", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
} elseif ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
} elseif ( ereg( "[][{}()*+?\\^$|]", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
//If the user err'd, print the error messages.
if ( $pass==1 ) {
//This first line is for ajax/javascript, comment it or delete it if this isn't your cup o' tea.
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo "<b>" . $errormessage . "</b>";
echo "<ul>";
echo $alert;
echo "</ul>";
// If the user didn't err and there is in fact a message, time to email it.
} elseif (isset($_REQUEST['message'])) {
//Construct the message.
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
//Mail the message - for production
mail($sendto, $subject, $message, $header, "-fstephanie#stephaniehenderson.com");
//This is for javascript,
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\").animate({opacity: 1.0}, 4000).hide(\"slow\"); $(':input').clearForm() </script>";
echo $thanks;
die();
//Echo the email message - for development
echo "<br/><br/>" . $message;
}
//If honeypot is filled, trigger the message that bot likely won't see.
} else {
echo "<script>$(\".message\").hide(\"slow\").show(\"slow\"); </script>";
echo $honeypot;
}
?>
If the message is echoing then it's not a problem with your javascript or html. I would suggest making a fresh PHP file with only the 1 line that attempts to send mail:
mail('youremailaddress#example.com', 'My Subject', 'This is a message');
Hardcode everything. If that works, then you know that it's probably not a problem with your host, and you need to examine that line and the variables to are passing to mail()