Empty page after form submit (PHP & Javascript) - php

I have a form script that sends an email after its been submitted. A javascript removes the form after its been submitted.
But when I submit my form it shows me the empty .php file.
Heres my index.html code:
<!--Here is container with email subscription-->
<div class="container-fluid yellow-container bg-mail">
<div class="row-fluid">
<div class="span12">
<h2>Laat hier je email adres achter, zodat wij weten dat je van de partij bent</h2>
<p>Deze uitnodiging geldt voor jou en een relatie!</p>
<form action="save.php" id="subscribe-form" method="post" name="subscribe-form">
<input type="email" name="email" placeholder="Hier je emailadres" id="email" class="email required">
<button class="btn btn-inverse" id="submit" type="submit" value="Subscribe">Count me in!</button>
</form>
</div>
</div>
</div>
save.php code:
<?php
if (isset($_POST['email'])) {
//Email information
$admin_email = "marco#daretodesign.nl";
$email = $_POST['email'];
//send email
mail($admin_email, "Inschrijving via Dukdalf", $email . " " . "heeft zich ingeschreven via de website", "Van:" . $email);
}
?>
javascript code:
//Subscribe Form
if($('#subscribe-form').length && jQuery()) {
$('form#subscribe-form').submit(function() {
$('form#subscribe-form .error').remove();
var hasError = false;
$('.required').each(function() {
if(jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Vul a.u.b. uw email in.'+labelText+'</div>');
$(this).addClass('inputError');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Vul a.u.b. een geldig email in.'+labelText+'</div>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
$('form#subscribe-form input.submit').fadeOut('normal', function() {
$(this).parent().append('');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#subscribe-form').slideUp("fast", function() {
$(this).before('<div class="error">Bedankt voor het inschrijven!</div>');
});
});
}
return false;
});
Thanks for help in advance :)

it shows you your blank php page because you after send email should redirect user to somewhere, perhaps with:
header('Location: http://www.example.com/');
exit;
Regards,
Marcelo

Related

How create an url dynamically in Jquery AJAX?

I have a reset password system in PHP.
First - the forgot password.php sends to the customer an email with a link to reset the password.
This one is composed of the email of the customer and a unique key code for resetting the password
this email is like :
Please click the following link to reset your password: .../resetpassword.php?email=pm.chaumien#me.com&code=5e1b876bb1e36
On this page... you have a form with 2 boxes for a new password.
<?php
include 'main.php';
// Output message
$email=$_GET['email'];
$code=$_GET['code'];
$msg = '';
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if (isset($_GET['email'], $_GET['code']) && !empty($_GET['code'])) {
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
$stmt = $pdo->prepare('SELECT * FROM accounts WHERE email = ? AND reset = ?');
$stmt->execute([$_GET['email'], $_GET['code']]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// If the account exists with the email and code
if ($account) {
if (isset($_POST['npassword'], $_POST['cpassword'])) {
if (strlen($_POST['npassword']) > 20 || strlen($_POST['npassword']) < 5) {
$msg = 'Password must be between 5 and 20 characters long!';
} else if ($_POST['npassword'] != $_POST['cpassword']) {
$msg = 'Passwords must match!';
} else {
$stmt = $pdo->prepare('UPDATE accounts SET password = ?, reset = "" WHERE email = ?');
// We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
$password = password_hash($_POST['npassword'], PASSWORD_DEFAULT);
$stmt->execute([$password, $_GET['email']]);
$msg = 'Password has been reset! You can now login!';
}
}
} else {
die('Incorrect email and/or code!');
}
} else {
die('Please provide the email and code!');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body id="register_bg">
<nav id="menu" class="fake_menu"></nav>
<div id="preloader">
<div data-loader="circle-side"></div>
</div>
<!-- End Preload -->
<div class="rsvp-form" id="login">
<aside>
<figure>
<img src="../img/logoBlack.png" width="64" height="64" data-retina="true" alt="" class="logo_sticky">
</figure>
<?php echo 'email='.$email.'&'.'code='.$code?>
<form action="resetpassword.php?email=<?=$_GET['email']?>&code=<?=$_GET['code']?" method="post">
<div class="form-group">
<label>Your password</label>
<input class="form-control" type="password" name="npassword" id="npassword">
<i class="icon_lock_alt"></i>
</div>
<div class="form-group">
<label>Confirm password</label>
<input class="form-control" type="password" name="cpassword" id="cpassword">
<i class="icon_lock_alt"></i>
</div>
<!-- Do Not Remove! -->
<p class="error"></p>
<p class="message"></p>
<!-- Do Not Remove! Ends! -->
<div id="pass-info" class="clearfix"></div>
<div class="text-right"><button type="submit" class="btn_1 rounded full-width add_top_30">Reset Password</button></div>
</form>
<!-- COMMON SCRIPTS -->
<script src="../js/jquery-2.2.4.min.js"></script>
<script src="../js/common_scripts.js"></script>
<script src="../js/main.js"></script>
<script src="../assets/validate.js"></script>
<script src="../assets/formreset.js"></script>
<!-- SPECIFIC SCRIPTS -->
<script src="../assets/pw_strenghtreset.js"></script>
</body>
For check this form I've a jquery with AJAX for the form action and the verification but on this one, it doesn't work.
$('.rsvp-form form').submit(function(event) {
var $password = $(this).find('input[id="npassword"]');
var $password1 = $(this).find('input[id="cpassword"]');
$('.rsvp-form p.error').show();
$('input[id="npassword"],input[id="cpassword"]').removeClass('error');
if ($password.val() === '') {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> Veuillez saisir un mot de passe, svp !');
$password.addClass('error').focus();
return false;
}
if ($password1.val() === '') {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> Veuillez saisir un mot de passe, svp !');
$password1.addClass('error').focus();
return false;
}
if ($password1.val() != $password.val()) {
$('.rsvp-form p.error').addClass('active').html('<i class="fa fa-exclamation"></i> les mots de passe ne correspondent pas !');
$password1.addClass('error').focus();
return false;
}
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find('input, button, textarea');
var serializedData = $form.serialize();
$inputs.prop('disabled', true);
request = $.ajax({
url: 'resetpassword.php?email=<?php echo $email; ?>&code=<?php echo $code; ?>',
type: 'post',
data: serializedData
});
request.done(function (response, textStatus, jqXHR){
$('.rsvp-form p.error').hide();
$('.rsvp-form p.message').html('success, password was changed').fadeOut(10000);
$('.rsvp-form form').find('input[type=text], textarea, select').val('');
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
'The following error occured: '+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop('disabled', false);
});
event.preventDefault();
});
});

Php contact form open a new page

I'm building a website and have I a php contact form.
Validation of the form and mail() function is working perfectly.
My php file for the form is handler.php.
Now to the problem. When I press the submit button and a error message is coming up, they comes up in a new blank page and that page is the same URL but it added /handler.php in the URL.
What i want to do is make the error messages show up under the form, and if it is no errors I want it to go to my thankyoumessage.html.
This is the php code for the form:
<?php
/*Set the mail of the reciever*/
$myemail = "mymail#example.com";
/*Display error message*/
function show_error($myError)
{
?>
<html>
<body>
<b>Var snäll och rätta till följande fel:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
/* Check inputs */
function check_input($data, $problem='error')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
// if ($problem && strlen($data) == 0)
// {
// show_error($problem);
// }
return $data;
}
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
?>
And this is the Html to the form:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control">
<label>Ditt namn</label>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate">
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control">
<label>Ämne</label>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3"></textarea>
<label>Meddelande</label>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
If you don't want to use AJAX, You can just let the mail() function process the form in the same page as the following :
<?php
// we declare empty error variables
$error = $error_email = $error_name = $error_subject = $error_message = "";
if (isset($_POST['submit']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$error_email = "Email adressen är inte giltig...";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
$error_name = "Du måste skriva in ditt namn...";
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
$error_email = "Du måste skriva in din email...";
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
$error_message = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/// You can add the subject validations here as well
if (empty($_POST['subject']))
{
$error_subject = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
if(mail($myemail, $subject, $mail))
{
/// We redirect to the thank you mesage uppon a successful message sending
header("Location:thankyoumessage.html");
}
else
{
// Failure message if the mail() function failed to trigger
$error = "Something wrong !";
}
}
?>
<form class="mt-5 ml-5 mr-5" method="POST" action="" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control" required >
<label>Ditt namn</label>
</div>
<!-- Error name -->
<div class="text-center mt-4 mb-4">
<?php echo $error_name;?>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate" required>
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<!-- Error email -->
<div class="text-center mt-4 mb-4">
<?php echo $error_email;?>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control" required>
<label>Ämne</label>
</div>
<!-- Error subject -->
<div class="text-center mt-4 mb-4">
<?php echo $error_subject;?>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3" required></textarea>
<label>Meddelande</label>
</div>
<!-- Error message -->
<div class="text-center mt-4 mb-4">
<?php echo $error_message;?>
</div>
<div class="text-center mt-4 mb-4">
<?php echo $error;?>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
It sounds like you need this in a single page, but your form is directing to a second page (handler.php). You might benefit from having all of the functionality in a single script that loads both the form and handles form submission. The algorithm might go something like this:
$showForm = $showThankYou = false;
$errorMessage = '';
//if form submitted
//check for errors
//if no errors
$showThankYou = true;
//else set error vars appropriately
$errorMessage = '...';
$showForm = true;
// else
$showForm = true;
From this point, you can include both your form and your thank you wrapped in conditionals. You can include your error message in your form html, as it will be blank when the form is first loaded.
if($showForm) {
// form code block
}
if($showThankYou) {
// thank you page
}
It is going to /handler.php because is set on the form action:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
If you want to stay on the same page after form submits, you have to leave action empty. Instead, you have to set a conditional that checks if submit is set:
if(isset($_POST['submit']){
include('handler.php');
}
Adding that code below your form will execute the script when the user hits submit (you have to modify it, it has to be an not a button).
That's one way to do it using exclusively PHP. You also can put all the code of sending mail inside a function, and execute it when submit is send:
function sendMail(){
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
}
Changing the submit code
<?php
include('handler.php');
if(isset($_POST['submit'])){
sendMail();
}
?>
There are any other ways, but this two maybe solve your problem in a way that only uses PHP.
Hope it helps.
PD: You have the same ID for the name and email input.
Sounds like you need JavaScript, since the user will never leave the page. If you make handler.php return some json instead of a page, this will be super easy. First of all, I would put all your HTML in a file called contact.html so you can reference a different page from the one you're currently on. If you add an empty <p class="errorMsg"></p> to the body wherever you want, it will be invisible until there's an error.
Then you can add the below scripts in a file called submitForm.js, adding <script src="submitForm.js"></script> to the head of contact.html.
const formElement = document.querySelector('form')
const formData = new FormData(formElement)
formElement.onsubmit = event => {
event.preventDefault()
fetch('/handler.php', { method: 'POST', body: formData })
.then(response => response.json())
.then(json => {
const errorElement = document.querySelector('errorMsg')
errorElement.textContent = json.errorMsg
if (json.errorMsg !== '') document.location = '/thankyoumessage.html'
})
}
To break it down, fetch is a really easy way to make an ajax request. Your user will stay on the current page, but your code will go out to the URL and get its data for use on the current page. fetch() makes the request, and then() handles it synchronously after it gets the response. Here, I'm chaining two then()s because I need to parse it into json before I can access that data. The last then() is how you would handle the form submission.
Learn more about fetch
Fetch is a new web API that relies on ES6 features and may not be compatible with older browsers. I still encourage you to use it, because even if IE11 support is necessary, all it takes is a polyfill and a syntax converter to do all the work for you.
Now, to make fetch work like this, you'll need to put something in handler.php. You can use all the code in your first snippet, leaving out the HTML. You can return JSON just by building a string and echoing it, no html necessary. You could accomplish that by changing your show_error() function calls to assigning an $errorMsg variable, like this.
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$errorMsg = "Email adressen är inte giltig...";
}
then at the end of the file, instead of HTML you can write the JSON string like so.
echo '{ "errorMsg" : "' . $errorMsg . '" }';
Now, if your form still hit that page with an Email error for example, you would see this:
{ "errorMsg" : "Email adressen är inte giltig..." }
... Obviously you don't want to see that, but your JavaScript can see that without your user looking at it, and the JavaScript knows exactly what to do with that data, like we saw above. Then you can add as many things as you want to that JSON, so your live JavaScript can do other things with it.
Learn more about JSON

PHP doesn't echo to Ajax request

I'm trying to send email with PHP using an Ajax request, but my "echo" on the PHP file just seems to not work and I have no idea why.
Thinking that my PHP code was wrong, I replaced my code with just an "echo" as posted below, but it still is not working.
I'm posting my HTML, JS, PHP and also the firebug response, which I don't quite understand.
HTML
<form id="contactForm" class="contact-form">
<div class="form-group form-icon-group">
<input class="form-control" id="name" name="name" placeholder="Nome" type="text" required title="Por favor, preencha esse campo." x-moz-errormessage="Por favor, preencha esse campo."/>
<i class="fa fa-user"></i>
</div>
<div class="form-group form-icon-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required title="Por favor, preencha esse campo corretamente." x-moz-errormessage="Por favor, preencha esse campo corretamente.">
<i class="fa fa-envelope"></i>
</div>
<div class="form-group form-icon-group">
<textarea class="form-control" id="message" name="message" placeholder="Qual sua mensagem?" rows="10" required title="Por favor, preencha esse campo." x-moz-errormessage="Por favor, preencha esse campo."> </textarea>
<i class="fa fa-pencil"></i>
</div>
<div>
<a id="btnEnviar" value="Enviar Email" class="btn btn-primary btn-lg">Enviar Email</a>
</div>
<div>
<label id="labelResposta" style="font-size: 22px; margin-top: 20px; display: none;">Email enviado com sucesso!</label>
</div>
<div id="messages"></div>
</form>
JS
$('#btnEnviar').click(function() {
$('#btnEnviar').html('Enviando...');
$('#btnEnviar').attr('disabled', 'disabled');
var formData = {
nome: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
// console.log(formData);
// console.log($("#contactForm").serialize());
if(!formData.nome) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Por favor preencha seu nome.');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
} else if(!formData.email) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Por favor preencha seu email.');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
} else if(!formData.message) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Por favor preencha sua mensagem.');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
} else {
$.ajax({
url: 'file:///home/phellipe/Desktop/projetos/phperin/email/email_processor.php',
type: "POST",
data: formData,
success: function(data) {
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').html('Email enviado com sucesso!');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
},
error: function(x, e){
console.log(x);
console.log(e);
if(x.status==0){
$('#labelResposta').html('Você não está online!\n Por favor, verifique sua conexão.');
}else if(x.status==404){
$('#labelResposta').html('URL não encontrada.');
}else if(x.status==500){
$('#labelResposta').html('Erro interno.');
}else if(e=='parsererror'){
$('#labelResposta').html('Erro de parse.');
}else if(e=='timeout'){
$('#labelResposta').html('Timeout.');
}else {
$('#labelResposta').html('Erro desconhecido.\n'+x.responseText);
}
$('#btnEnviar').html('Enviar Email');
$('#btnEnviar').removeAttr('disabled');
$('#labelResposta').fadeIn();
setTimeout(function() {
$('#labelResposta').fadeOut();
}, 3000);
}
});
}
return false;
});
PHP (test)
<?php echo "string"; ?>
PHP (real)
<?php
$sender_name = trim(ucfirst($_REQUEST['nome']));
$sender_email = trim($_REQUEST['email']);
$sender_message = trim(ucfirst($_REQUEST['message']));
$html_email = '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PhPerin</title>
</head>
<body>
<p>Olá</p>
<p>Notificamos que <em>' . $sender_name . '</em> entrou em contato</p>
<p>Deixou a seguinte mensagem:</p>
<p>' . $sender_message . '</p>
<p>Você pode entrar em contato pelo seguinte email ' . $sender_email . '</p>
</body>
</html>';
require_once("send_email.php");
echo "string";
?>
Firebug Response
readyState 4
responseText "<?php echo "string"; ?>"
status 200
statusText "parsererror"
I wonder if you need to escape those double quotes. Where it says
<meta charset="UTF-8">
try
<meta charset=\"UTF-8\">

How to submit a form with ajax and php

I am trying to add a change password function on my site. I decided that i would try using ajax so the site does not have to update itself. But i have one problem. When i submit the form to my PHP file nothing happends i just get the success from the ajax file. And the password is not change in my SQL db.
This is the html file.
<div class="boxPW">
<div class="boxInner">
<img class="closeBox" style="float: right;" src="images2/zoom/closebox.png" />
<h2>Endre passord ditt</h2>
<div id="lineBreak" style="margin-top: -19px; width: 70%;"></div>
<h4>Skriv inn et nytt passord for <?php echo $fname.' '.$lname.' ';?>
Vi anbefaler at du oppretter et unikt passord –
et du ikke bruker på noen andre nettsteder. <h4>
<div class="boxInner2">
<form id="changePw" name="changePw" method="POST" action="">
<input type="password" id="oldPw" name="oldPw" placeholder="Nåværende passord" />
<label id="error_oldPw" class="error">Fyll inn nåværende passord</label>
<p style="margin: 0; width:100px; font-size:9px; color: #38C6DA; ">Glemt ditt passord?</p>
<div class="divider"></div>
<input type="password" id="newPw" name="newPw" placeholder="Nytt passord"/>
<label id="error_newPw" class="error">Fyll inn nytt passord</label>
<div class="divider"></div>
<input type="password" id="conNewPw" name="conNewPw" placeholder="Bekreft nytt passord"/>
<label id="error_conNewPw" class="error">Gjenta ditt passord</label>
<div class="divider"></div>
<input id="buttonpw" class="button" type="button" name="submit" value="Endre passord" />
</form>
</div>
</div>
</div>
And here are my Jquery file (returnPwBox.js)
$(document).ready(function() {
$('.error').hide();
$('#buttonpw').click(function(){
//Validate inputData
$('error').hide();
var oldPw = $("input#oldPw").val();
if(oldPw == ""){
$("label#error_oldPw").show();
$("input#oldPw").focus();
return false;
}
var newPw = $("input#newPw").val();
if(newPw == ""){
$("label#error_newPw").show();
$("input#newPw").focus();
return false;
}
var conNewPw = $("input#conNewPw").val();
if(conNewPw != newPw){
$("label#error_conNewPw").show();
$("input#conNewPw").focus();
return false;
}
var dataString = 'oldpw='+ oldPw + '&newPw=' + newPw + '&conNewPw=' + conNewPw;
$.ajax({
type: "POST",
url: "changePw.php",
data: dataString,
success: function(){
$('.boxInner2').html("<div id='message' style='width: 300px;'></div");
$('#message').html("<h2>Endring fullført</h2>")
.append("<h4>Ditt passord er nå endret</h44>")
.hide()
.fadeIn(1000, function(){
$('#message').append("<img id='checkmark' src='imgaes2/pitcharrow.gif'/>");
});
}
});
return false;
});
And here are my changePw.php:
<?php
include('conn.php');
require_once('auth.php');
include('fetchMemData.php');
function clean($str){
$str=#trim($str);
if(get_magic_quotes_gpc());{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$id=$_SESSION['SESS_MEMBER_ID'];
$oldPw = clean($_POST['oldPw']);
$newPw = clean($_POST['newPw']);
$conNewPw = clean($_POST['conNewPw']);
$oldPw = strip_tags($oldPw);
$newPw = strip_tags($newPw);
$conNewPw = strip_tags($conNewPw);
$oldPw = md5($oldPw);
$newPw = md5($newPw);
$conNewPw = md5($conNewPw);
if($oldPw == $password)
{
mysql_query("UPDATE reguser SET password='$newPw' WHERE mem_id='$id'");
}else{
echo ("Feil nåværende passord");
}
?>
If anyone see any errors or any suggestions, shout out! I need some help:)
Based on the code you wrote $password value is not asigned (unless you did it in another file) therefore $password is NULL , and the if:
if($oldPw == $password)
{
mysql_query("UPDATE reguser SET password='$newPw' WHERE mem_id='$id'");
}else{
echo ("Feil nåværende passord");
}
returns false

Form emailing with script

I'm french (sorry for the english) and I'm looking for a solution to this problem.
I made a form witch send a mail to the adress I indicate in the contact.php file.
The problem is that the mail I receive does not contain the "emailSchool" variable.
Here are some of my files :
My html file :
<div id="formulaire">
<form id="myForm" action="contact.php" method="post">
<label for="emailName">Nom et prénom:</label>
<input name="emailName" type="text" id="emailName"/>
<label for="emailFrom">Email:</label>
<input name="emailFrom" type="text" id="emailFrom"/>
<label for="emailSchool">Ecole :</label>
<input name="emailSchool" type="text" id="emailSchool"/>
<label for="emailMessage">Message: (optionnel)</label>
<textarea name="emailMessage" cols="30" rows="9" id="emailMessage"></textarea>
<input style="padding-left:5px; width:80px; height:32px;" type="image" src="images/send.png" id="submit" class="submit" alt="ENVOYER"/>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
My script :
$("#submit").click(function(){
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailFromVal = $("#emailFrom").val();
if(emailFromVal == '') {
$("#emailFrom").addClass("error");
hasError = true;
} else if(!emailReg.test(emailFromVal)) {
$("#emailFrom").addClass("error");
hasError = true;
}
else
{
$("#emailFrom").removeClass("error");
}
var nameVal = $("#emailName").val();
if(nameVal == '') {
$("#emailName").addClass("error");
hasError = true;
}
else
{
$("#emailName").removeClass("error");
}
var schoolVal = $("#emailSchool").val();
if(schoolVal == '') {
$("#emailSchool").addClass("error");
hasError = true;
}
else
{
$("#emailSchool").removeClass("error");
}
var messageVal = $("#emailMessage").val();
if(messageVal == '') {
$("#emailMessage").addClass("error");
hasError = true;
}
else
{
$("#emailMessage").removeClass("error");
}
if(hasError == false) {
$(this).hide();
$("#myForm").fadeOut("fast", function(){
$("#myForm").before('<img src="images/loading.gif" alt="Loading" id="loadingImage" />');
$.post("contact.php", { emailFrom: emailFromVal, emailName: nameVal, emailSchool: schoolVal, emailMessage: messageVal },
function(data){
$("#loadingImage").fadeOut("fast", function() {
$("#loadingImage").before('<p>Votre inscription a bien été pris en compte, nous vous enverrons un email pour confirmer !</p>');
});
}
);
});
}
return false;
}
And my .php file :
<?php
$nameVal=$POST['emailName'];
$emailFromVal=$POST['emailFrom'];
$messageVal=$POST['emailMessage'];
$schoolVal=$POST['emailSchool'];
$to='mymail#gmail.com';
$sujet='Nouvel incrit JEIC CHALLENGE !'.$emailFrom;
$msg='Message :'.$emailMessage;
$mailHeader = "From = {$emailFrom}";
$mailBody = "Nom = {$emailName} Ecole = {$emailSchool}";
mail($to, $sujet, $msg, $mailBody , $mailHeader);
?>
The problem is that I don't have the "School" field in the mail I receive.
Maybe somebody have a solution ?
Thanks a lot.
You are defining:
$schoolVal=$POST['emailSchool'];
And using in your header:
$emailSchool
Maybe change {$emailSchool} into {$schoolVal} ....
You mix POST names and locals...

Categories