How do I return my Form errors - javascript

My php runs but for some reason my variables are not being communicated. What am I doing incorrectly? I am trying to relay the message through ajax and i can't seem to get any type of error or success message to pop up, no matter where I put it in my php..which leads me to believe that the problem lies inside my ajax/javascript functions. The ajax should place the message straight in the defined . I also realize this has been asked before on here but I have truly looked at a lot of them and still can not figure out what's wrong. Thanks guys, sorry for the wall.
AJAX
<!-- Email -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('#sub_result').html("");
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'phEmail.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for email ---------------
if (data.errors.email) {
$('#sub_result').addClass('class="error"'); // add the error class to show red input
$('#sub_result').append('<div class="error">' + data.errors.email + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#sub_result').append('<div class="success" >' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false)
{
$errors['email'] = 'Email is not valid';
}
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
}
// if there are items in our errors array, return those errors============================
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
//variables===============================================================================
$servername = "localhost";
$username = "ghostx19";
$password = "nick1218";
$dbname = "ghostx19_samplepacks";
$user = $_POST['email'];
// Create connection======================================================================
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Connection failed";
}
//add user================================================================================
$sql = "INSERT INTO users (email)
VALUES ('$user')";
if ($conn->query($sql) === TRUE) {
$data['success'] = true;
$data['message'] = 'Subscribed!';
} else {
$errors['email'] = 'Error';
}
$conn->close();
// message to me==========================================================================
$to = 'garvernr#mail.uc.edu';
$subject = 'New subscription';
$message = $_POST['email'];
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
//message to user=========================================================================
$to = $_POST['email'];
$subject = 'Subscribed!';
$message = 'Hello new member,
Thank you for becoming a part of samplepackgenerator.com. You are now a community member and will recieve light email updates with the lastest information. If you have recieved this email by mistake or wish to no longer be apart of this community please contact nickgarver5#gmail.com
Cheers!,
-Nick Garver ';
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
?>
HTML
<!-- Subscription -->
<div class="container shorter">
<div class="no-result vertical-align-outer">
<div class="vertical-align">
<form action="phEmail.php" method="POST">
<!-- EMAIL -->
<div id="email-group" class="form-group">
<label for="email"></label>
<input type="text" class="email" name="email" placeholder="Enter your email">
<button type="submit" class="emailbtn">Subscribe</button>
<span></span>
<!-- errors -->
</div>
</div>
</div>
</div>
<br>
<br>
<div id="sub_result">
</div>

You just need to use json_encode in your PHP becuase your data type is json and you are expecting the response in json format like that
if (!empty($error)){
// your stuff
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
}
else {
// your stuff
$data['success'] = "SUCCESS MESSAGE";
$data['errors'] = false;
echo json_encode($data);
}

That's because you forgot to encode your $data array. Do echo json_encode($data); just before your ending PHP tag(?>), like this:
// your code
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo json_encode($data);
?>

Your php don't return any value, add a simple "echo" line at the end:
...
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo $data['message'];
?>
And in js (if all the other code is correct) you receive the message.

Your php file doesn't send anything to the output.
Add a line
exit(json_encode($data));
to your php file on the line where you want to return your reply.

Related

run PHP script in JS file

I have minimal knowledge in php and js. Im trying to get value from my form once submit button has been click then trigger my php script.
Js file:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Here's my php script:
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
if (isset($_REQUEST['submit'])) {
$to = "example#mail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
// Verify the reCAPTCHA response
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['g-recaptcha-response']);
// Decode json data
$responseData = json_decode($verifyResponse);
// If reCAPTCHA response is valid
if ($responseData->success) {
$headers = "From:" . $name . '<' . $from . '>' . PHP_EOL;
$headers .= "Reply-To:" . $to . PHP_EOL;
$headers .= "MIME-Version 1.0" . PHP_EOL;
$headers .= "Content-Type: text/html; charset=UTF-8" . PHP_EOL;
$headers .= "X-Mailer: PHP/" . phpversion();
$status = mail($to, $subject, $message, $headers);
echo "<pre>";
var_dump($status);
if ($status) {
echo '<p>Your message has been sent. We will get in touch with you soon. Thank you!</p>';
} else {
echo '<p>Something went wrong. Please try again!</p>';
}
} else {
echo 'error';
}
} else {
echo 'Please check on the reCAPTCHA box.';
}
}
?>
Here's my form code in index.php. I have 3 fields name, email and message:
<?php include_once 'form-to-email.php';?>
<form id="form" method="post" action="">
<div class="input-group">
<input type="text" id="name" name="name" class="input-demo" placeholder="Your Name">
<span id="invalid-name">
Please enter at least 2 chars
</span>
</div>
<div class="input-group">
<input id="email" type="email" name="email" class="input-demo" placeholder="Email Address">
<span id="invalid-email">
Please enter valid email
</span>
</div>
<div class="input-group">
<textarea id="message" name="message" placeholder="Message">
</textarea>
<span id="invalid-message">
Please write something for us
</span>
</div>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>">
</div>
<input type="submit" name="submit" id="button" class="demo" value="Book a Demo">
</form>
I get console.log empty values. Is this the right path or calling php is simply not doable?
Update
It now echos true and message sent.
Based on your question you are looking simply to submit a form and access the value in your php script. But it seems you are trying to submit the form via an ajax request. The first place to start is in your javascript code. The first thing I see is that you are calling a couple functions that are not defined so you never pass the if check and get to where it is supposed to say 'got here':
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here'); // you never get to this point
grecaptcha is not yet defined and I don't see any function definition for validateFields() so that fails as well. As a temporary fix while you are debugging it, comment out the if check like this so you can focus on the xhr request:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
// Comment out the following two lines
// so you can focus on getting the XHR request to work
// let response = grecaptcha.getResponse();
// if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
// } Comment out the closing bracket to match the comments from above
document.getElementById('button').style.cursor = 'not-allowed';
});
Ok, now when you hit submit, you should be sending the form data to your php script. To test out what shows up in the php script you can bail out early to see the contents of your $_POST variable.
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
// Echo out the word success to make sure you got to this point.
// Then echo out the contents of your $_POST variable to see what is in it.
echo "Success";
var_dump($_POST);
exit; // exiting here bails out early.
// When you var_dump out your $_POST variable you will notice that
// $_POST['submit'] is not set since you don't have an input field
// for that value.
if (isset($_POST['submit'])) {
$to = "example#email.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
. . .
Now, since you decided to do this via ajax, it will be a bit trickier to see the echo statement and the var_dump. To find out if it is working you need to use your dev tools network tab (F12 -> Network). Under the network tab you will see something like this:
Each time you hit submit, it should show a new line representing that request to the server. You can select a line and inspect the payload, preview, response tabs to see what was sent and what was received.
I hope this helps point you in the right direction. I'm not going to get into the issues with validating re-captcha and form validation. Those are topics for another question once you get the basic form working.
Cheers!
Based on this answer, change the way you're calling the php function.
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.open('POST', 'form-to-email.php?submit'); //don't forget submit here
xhr.send(data);
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Also, try using $_REQUEST instead of $_POST in PHP file, as in:
if (isset($_REQUEST['submit'])) {
echo 'HERE IN PHP';
}

How to reset ReCaptcha box on successful form submission

I have a form on my website that uses ReCaptcha2. After the form is successfully completed and you get the success message, the form fields (name, email, message) are cleared but the ReCaptcha box remains ticked. Is there any way to clear this box after successful submission of the form or is there a way to permanently show the success message (as opposed to it fading out after a few seconds) and remove the entire form from the page. Ideally the success message would remain on the page until it is refreshed. I still want the existing other error messages to fade in and out as they currently do.
At present the initial Captcha error message reads "You did not check the box, a bot was detected or you have already sent this form. Please check the box or refresh this page & try again". The refresh suggestion is to cover the instance where the user presses send again and ReCaptcha has been left ticked from a previous successful submission (ie they try to send the form twice). Hence why I would like to implement one of the solutions posed in my question. Thanks in advance for any help given. Here is working URL of the form (at the bottom of the page)
http://www.topolinowebdesigns.uk/test-site/aerocoat/index-v2.html
<?php
/*
+-----------------------------------------------------+
| GOOGLE reCAPTCHA YOUR PUBLIC AND PRIVATE KEY |
| You can collect public and secret key from here: |
| https://www.google.com/recaptcha/admin |
+-----------------------------------------------------+
*/
$recaptcha_secretkey = "My secret key";
// GOOGLE reCAPTCHA Validation Check
ini_set('display_errors',1); error_reporting(E_ALL);
$message = "";
$status = "false";
if( isset( $_POST['submit'] ) ) {
$userIP = $_SERVER["REMOTE_ADDR"];
$recaptchaResponse = $_POST['g-recaptcha-response'];
$secretKey = $recaptcha_secretkey;
$request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$recaptchaResponse}&remoteip={$userIP}");
if( !strstr( $request, "true" ) ) {
$message = '<p align="justify"><strong>Captcha Error!</strong> You did not check the box, a bot was detected or you have already sent this form. Please check the box or refresh this page & try again.</p>';
$status = "false";
} else {
require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/class.smtp.php');
$mail = new PHPMailer();
//$mail->SMTPDebug = 3; // Enable verbose debug output
/*$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'my hostname'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'my username'; // SMTP username
$mail->Password = 'my password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to*/
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['form_name'] != '' AND $_POST['form_email'] != '' ) {
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_message'];
$subject = 'New Message | Contact Form';
$botcheck = $_POST['form_botcheck'];
$toemail = 'my email address'; // Your Email Address
$toname = 'my name'; // Your Name
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$mail->Subject = $subject;
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = "$name $email $message $referrer";
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$message = '<p align="justify"><strong>Success!</strong> We have received your message and will get back to you as soon as possible.</p>';
$status = "true";
else:
$message = '<p align="justify"><strong>Attention!</strong> Your message could not be sent due to an unexpected error. Please try again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '</p>';
$status = "false";
endif;
} else {
$message = '<p align="justify"><strong>Bot Detected!</strong> Your efforts are futile!</p>';
$status = "false";
}
} else {
$message = '<p align="justify"><strong>Warning!</strong> Please complete all the fields and try again.</p>';
$status = "false";
}
} else {
$message = '<p align="justify"><strong>Unexpected Error!</strong> Please try again later.</p>';
$status = "false";
}
}
$status_array = array( 'message' => $message, 'status' => $status);
echo json_encode($status_array);
}
?>
In addition here is the validation script that runs on the html page just after the form ends.
<script>
$("#contact_form").validate({
submitHandler: function(form) {
var form_btn = $(form).find('button[type="submit"]');
var form_result_div = '#form-result';
$(form_result_div).remove();
form_btn.before('<div id="form-result" class="alert alert-success" role="alert" style="display: none;"></div>');
var form_btn_old_msg = form_btn.html();
form_btn.html(form_btn.prop('disabled', true).data("loading-text"));
$(form).ajaxSubmit({
dataType: 'json',
success: function(data) {
if( data.status === 'true' ) {
$(form).find('.form-control').val('');
}
form_btn.prop('disabled', false).html(form_btn_old_msg);
$(form_result_div).html(data.message).fadeIn('slow');
setTimeout(function(){ $(form_result_div).fadeOut('slow') }, 8000);
}
});
}
});
</script>

if(isset($_POST['btn-save'])) doesn't return true

Yep, this old chesnut I'm afraid. I've read through a lot of the previous answers to this question but I cannot get into this if statement even though 'btn-save' is definitely set as the name attribute on my submit button.
I'm using the code from this tutorial to post form data to my database: http://www.phpzag.com/ajax-registration-script-with-php-mysql-and-jquery/
My site structure is like this:
- root
- public_html
- js
app.js
register.php
db_connect.php
form_page.php
My register.php file looks like this and I've added an echo inside the if statement:
<?php
include_once("db_connect.php");
if(isset($_POST['btn-save'])) {
echo "in if";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_id = $_POST['email_id'];
$address_1 = $_POST['address_1'];
$address_2 = $_POST['address_2'];
$address_3 = $_POST['address_3'];
$city_town = $_POST['city_town'];
$county = $_POST['county'];
$post_code = $_POST['post_code'];
$entrant_type = $_POST['entrant_type'];
$chosen_store = $_POST['chosen_store'];
$chosen_charity = $_POST['chosen_charity'];
$agree_terms = $_POST['agree_terms'];
$sql = "SELECT user_email FROM tbl_big_challenge_registrations WHERE user_email='$email_id'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!$row['user_email']){
$sql = "INSERT INTO tbl_big_challenge_registrations('uid', 'first_name', 'last_name', 'user_email', 'address_1', 'address_2', 'address_3', 'town_city', 'county', 'postcode', 'entrant_type', 'crew_store', 'charity', 'agree_terms') VALUES (NULL, '$first_name', '$last_name', '$email_id', '$address_1', '$address_2', '$address_3', '$city_town', '$county', '$post_code', '$entrant_type', '$chosen_store', '$chosen_charity', 'agree_terms', NULL)";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
echo "registered";
} else {
echo "1";
}
}
?>
My db_connect.php file looks like this (with dummy values for purpose of this post):
<?php
/* Database connection start */
$servername = "servername.com";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My form_page.php form looks like this:
<form id="2017-challenge-form" method="post" data-abide>
<!-- form fields are here -->
<input id="btn-submit" type="submit" name="btn-save" value="submit">
</form>
And finally my app.js looks like this:
$('document').ready(function() {
/* handle form submit */
function submitForm() {
var data = $("#2017-challenge-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").val('Submitting...');
},
success : function(response) {
if(response==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").val('Submit');
});
} else if(response=="registered"){
$("#btn-submit").html('<img src="ajax-loader.gif" /> Signing Up ...');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".register_container").load("welcome.php"); }); ',3000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").val('Submit');
});
}
}
});
return false;
}
$("#2017-challenge-form").submit(function(event){
// cancels the form submission
event.preventDefault();
// jumps into ajax submit function
submitForm();
});
});
I have a breakpoint set just inside the ajax success and on submission of the form I would expect the response to have a value of 'registered' (just like the Demo from the PHPZag site: http://phpzag.com/demo/ajax-registration-script-with-php-mysql-and-jquery/
But I get an empty string:
Can anybody see what I'm doing wrong or am missing?
I changed the input to a button as per the demo site and this worked. As per the comment by #frz3993 the btn-save wasn't getting added to the data so the if(isset($_POST['btn-save'])) was never true as it wasn't finding it.

Email sending with AngularJS and PHP

I have created an application in AngularJS and it has an email contact form and it sends emails using PHP file in server.
Here's my Controller.js part in AngularJS:
$scope.feedbacksubmit= function (){
var name1 = document.getElementById("name").value;
var email1 = document.getElementById("email").value;
var message1 = document.getElementById("message").value;
$http({
url: "http://boost.meximas.com/mobile/email.php",
method: "POST",
data: { name: name1, email: email1, message:message1 }
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data != 0){
$scope.hide();
//$scope.closeFeedback();
}else{
$scope.showEmailError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
$scope.showAlertNetwork();
$scope.hide();
});
};
Here's my PHP Code:
<?php
$array = json_decode(file_get_contents('php://input'), true);
$name = $array['name'];
$email = $array['email'];
$message = $array['message'];
if (($name=="")||($email=="")||($message==""))
{
printf("0");
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("mygmail#gmail.com", $subject, $message, $from);
}
?>
The problem arises when I fill in the contact form and hit the Send button. I'm getting $scope.showEmailError();. But I get the email without problem.
And if I try to hit the button without filling the form still getting same $scope.showEmailError(); message.
Why don't you use model values from input? It looks like you try to use AngularJS but you still think with other frameworks in mind
In the following example I'm sending model to php script, if NAME is not filled then PHP returns 404 error and it's handled in AngularJS $http via .error handler. You don't have to add so much extra logic to success to deal with it
http://plnkr.co/edit/sw9RRXb3kdEWXszJdwX3?p=preview
html
<input type="text" ng-model="formData.name" placeholder="name">
<input type="text" ng-model="formData.email" placeholder="email">
<input type="text" ng-model="formData.message" placeholder="message">
javascript
$scope.formData = {
'name': '',
'email': '',
'message': ''
};
$scope.postData = function () {
$http.post('http://edeen.pl/form.php', $scope.formData)
.success(
function(data){
$scope.response = data.replace(/\ /g, ' ').replace(/\n/g, '<br/>') //format response
})
.error(
function(data){
$scope.response = data
})
}
php
$input = json_decode(file_get_contents('php://input'));
if($input->name === ''){
header("HTTP/1.0 404 Not Found");
echo "Something went terribly wrong, missing name maybe?";
return;
}
header('Content-Type: application/json');
var_dump($input);
<?php
$data = json_decode(file_get_contents("php://input"),true);
$name = $data->name;
$email = $data->email;
$sujet = $data->sujet;
$contenu = $data->contenu;
if($name && $email && $sujet && $contenu){
$destinataire = 'bercybilingualschool#gmail.com';
// Pour les champs $expediteur / $copie / $destinataire, séparer par une virgule s'il y a plusieurs adresses
$expediteur = $email;
$copie = 'sss17#gmail.com';
$copie_cachee = 'xxx#xxx.xxx';
$objet = $sujet; // Objet du message
$headers = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // l'en-tete Content-type pour le format HTML
$headers .= 'Reply-To: '.$expediteur."\n"; // Mail de reponse
$headers .= 'From: '.$name.'<'.$name.'>'."\n"; // Expediteur
$headers .= 'Delivered-to: '.$destinataire."\n"; // Destinataire
$headers .= 'Cc: '.$copie."\n"; // Copie Cc
$headers .= 'Bcc: '.$copie_cachee."\n\n"; // Copie cachée Bcc
$message = '<div style="width: 100%; text-align: justify; font-weight: bold">hello</div>';
mail($destinataire, $objet, $message, $headers);
}else{
}
?>

PHP and Javascript - Problems with undefinded variable

Hey guys i am very new to this so i am sorry if there is just something completely stupid i am missing here. I have the following Sign Up Form. And in the URL http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de i am trying to submit the value e. However, in all cases e is simply empty or undefined:
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$p = $_POST['p'];
$e = $_GET['e'];
echo "test";
echo "$e";
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM team WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "UPDATE team
SET username='$u',password='$p_hash',ip='$ip',signup=now(),lastlogin=now(),notecheck=now()
WHERE email='$e'";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>yoursitename Message</title></head>
<body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">
<div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
<img src="http://www.rockaholics-cologne.de/root/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">Account Activation</div>
<div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
I do get new entries into the database when i fill out the form. But it does neither send me an email or UPDATE the database at the specified email. It simply updates all the entries with a blank email. The echo "$e" within the script also return nothing.
I used this code to check:
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
$e = $_GET['e'];
echo "$e";
?>
And in this case it does return an array with [e]=cataras#gmx.de and it also prints out $e. But why doesnt it work in the other skript? I'm using the exact same methods to get e from the URL.
When i run my Javascript function:
function signup(){
var u = _("username").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&p="+p1);
}
}
I get Uncaught ReferenceError: e is not defined. And the site stops at "please wait...". I just took out the +e+ in the js to get to the php above. Sorry for the long post but i am really running out of ideas. THANKS in advance!!!
I think $_GET['e'] is not working in your original script because it's not getting passed to that processing script from your form page. I accessed the URL you provided (http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de). Note that when you submit your form, the value of "e" in your URL is not being passed to whatever is processing your script. In your form, you need to either do this:
<form action="{yourscripturl}?e=<?php echo $_GET['e']?>" {rest of form tag}>
Or, add a hidden to hold the value of "e", and then use $_POST['e'] on your processing script instead of $_GET['e'].
<input type="hidden" name="e" value="<?php echo $_GET['e']?>" />

Categories

Resources