Why my Ajax request isn't working with post method? - javascript

I come to ask for help because I have a problem that persists for three days and I can't understand where the problem is. I have a form on an HTML page here :
<form id="contactformpage">
<div class="messages"></div>
<div class="form-group row">
<label for="societepage" class="col-sm-6 col-form-label">Société</label>
<div class="col-sm-6 champ">
<input type="text" name="societe" class="form-control" id="societepage" placeholder="Nom de la société" aria-describedby="indicsocietepage">
<small id="indicsociete" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="adressepage" class="col-sm-6 col-form-label" >Adresse</label>
<div class="col-sm-6 champ">
<input type="text" name="adresse" class="form-control" id="adressepage" placeholder="Adresse">
</div>
</div>
<div class="form-group row">
<label for="codepostaletvillepage" class="col-sm-6 col-form-label" >Code postal & ville</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="codepostaletville" id="codepostaletvillepage" placeholder="Code postal & ville">
</div>
</div>
<div class="form-group row">
<label for="contactpage" class="col-sm-6 col-form-label">Nom du contact</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="contact" id="contactpage" placeholder="Nom du contact">
</div>
</div>
<div class="form-group row">
<label for="telephonepage" class="col-sm-6 col-form-label">Téléphone</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="téléphone" id="telephonepage" placeholder="Numéro de téléphone" aria-describedby="indictelephonepage">
<small id="indictelephonepage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="mailpage" class="col-sm-6 col-form-label">Adresse mail</label>
<div class="col-sm-6 champ">
<input type="email" class="form-control" name="mail" id="mailpage" placeholder="Entrez votre adresse mail" aria-describedby="indicmailpage">
<small id="indicmailpage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="selecmarque" aria-describedby="indicmarquepage"> Marque du véhicule </label>
<div class="col-sm-6 champ">
<select class="form-control" name="marque" style="height:20px;padding-bottom:0;padding-top:1;" onchange="generechoixmodele('selecmarque','apreschoixmarquepage','apreschoixmodelepage','nommodelepage','choixmodelepage','choixtypepage');" id="selecmarque">
<option selected> Séléctionnez </option>
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmarquepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix de la marque -->
<label class="col-sm-6 col-form-label" for="apreschoixmarquepage" aria-describedby="indicmarque" id="nommodelepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="modele" style="height:20px;padding-bottom:0;padding-top:1;" id="choixmodelepage" onchange="generechoixtype('selecmarque','choixmodelepage','apreschoixmodelepage','nomtypepage','choixtypepage');">
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmodelepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix du modèle -->
<label class="col-sm-6 col-form-label" for="apreschoixmodelepage" aria-describedby="indicmarque" id="nomtypepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="type" style="height:20px;padding-bottom:0;padding-top:1;" id="choixtypepage">
</select>
</div>
</div>
<p> Je souhaite recevoir les catalogues suivants (dynamique)</p>
<div id="choixcataloguepage">
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="commentairepage">Commentaire</label>
<div class="col-sm-6 champ">
<textarea class="form-control" name="commentaire" id="commentairepage" rows="1"></textarea>
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-6 col-form-label">Captcha</label>
<div class="col-sm-6 champ">
<h6> Captcha à rajouter après </h6>
</div>
</div>
<input type="submit" class="btn" id="submitpage">
</form>
And when I click on the button of this form, I send the data entered by the user thanks to an Ajax request on a php page:
$(document).ready(function(){
$("#submitpage").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'sendform.php',
dataType: "JSON",
data: {
societe : $("#societepage").val(),
adresse : $("#adressepage").val(),
codepostaletville : $("#codepostaletvillepage").val(),
contact : $("#contactpage").val(),
telephone : $("#telephonepage").val(),
mail : $("#mailpage").val(),
marqueclient : $("#selecmarque").val(),
modeleclient : $("#choixmodelepage").val(),
typeclient : $("#choixtypepage").val(),
commentaire : $("#commentairepage").val()
},
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contactformpage').find('.messages').html(alertBox);
// empty the form
$('#contactformpage')[0].reset();
}
}
})
});
});
I know it's possible to do $(this).serialize() for forms directly but I'd like to do that already. Here is the PHP script in question, so I send my data with the POST method, the problem is that this script tells me all the time "Form is empty" which means that the data was not sent with POST (since $ _POST is empty). And when I try to make an echo ($_SERVER['HTTP_X_REQUESTED_WITH']), the php script returns an empty string, which means that the Ajax request was not made.
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
AND ALSO SMTP TO SEND THE EMAILS
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer/PHPMailer-master/src/Exception.php';
require 'PHPMailer/PHPMailer-master/src/SMTP.php';
require 'PHPMailer/PHPMailer-master/src/OAuth.php';
require 'PHPMailer/PHPMailer-master/src/POP3.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'lyes.tifoun#hotmail.fr';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'lyestfn#gmail.com';
$sendToName = 'Lyes Tifoun';
// subject of the email
$subject = 'New message from contact form';
// smtp credentials and server
$smtpHost = 'smtp.gmail.com';
$smtpUsername = 'nom_utilisateur';
$smtpPassword = 'mdp';
$fields = array('societe' => 'Société', 'adresse' => 'Adresse', 'codepostaletville' => 'Code postal et ville', 'contact' => 'Nom du contact', 'téléphone' => 'Numéro de téléphone', 'mail' => 'Adresse mail', 'marque' => 'Marque du véhicule', 'modele' => 'Modèle du véhicule', 'type' => 'Type du véhicule', 'commentaire' => 'Commentaire');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
error_reporting(E_ALL & ~E_NOTICE);
try {
if (count($_POST) == 0) {
throw new \Exception('Form is empty');
}
$emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = gethostbyname($smtpHost);
$mail->Port = 587;
$mail->isHTML(true);
$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->Subject = $subject;
$mail->Body = 'test';//$emailTextHtml;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
$mail->Debugoutput = 'html';
if (!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (\Exception $e) {
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
I would like to understand why my request doesn't work because I don't think I made any syntax or other errors.
Here is the script used for the JQuery library in my HTML file.
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
And I use WAMPServer to run my site locally, I already did my research but could the problem come from there by chance?
Thank you in advance

I come back to you to inform you that my data is finally sent with $_POST as shown by the network panel:
enter image description here
I've also made a var_dump($_SERVER) and the $_SERVER['HTTP_X_REQUESTED_WITH'] value is "XML HTTPREQUEST" which indicates that the Ajax request has been launched. Now I have an other problem : I don't have a client-side response: currently the program seems to validate the condition if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') and I have an echo($encoded) in JSON format as shown below :
enter image description here
Therefore I should have a client-side response, which is not the case actually.
Thanks a lot for your responses and sorry for my bad english.

Related

Novice developer - Trouble with php contact form templates - probably something dumb

I am a novice developer and for some reason I have never been able to get a php contact form to function properly. I've tried templates from bootstrapious and reusable forms but I've never been able to get them to work. My ultimate goal is to have a form with recaptcha but I can't get just a regular old form to work. Here are the codes from my latest attempt. I've been working on this for days and I feel like I'm missing something small and stupid. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Form Tutorial by Bootstrapious.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet" type="text/css">
<link href="custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">
<h1>Contact form Tutorial from Bootstrapious.com</h1>
<p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.</p>
<p class="lead">This file uses PHPMailer to send the emails.</p>
<form id="contact-form" method="post" action="contact-2.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> These fields are required. Contact form template by Bootstrapious.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" integrity="sha256-dHf/YjH1A4tewEsKUSmNnV05DDbfGN3g7NMq86xgGh8=" crossorigin="anonymous"></script>
<script src="contact-2.js"></script>
</body>
PHP
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'uprightjared#gmail.com';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'uprightjared#gmail.com';
$sendToName = 'Demo contact form';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone',
'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back
to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try
again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by
error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml = "<h1>You have a new message from your contact form</h1>
<hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses
by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version
of the HTML email, very handy
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
JS
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact-2.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and
apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-
dismissable"><button type="button" class="close" data-dismiss="alert" aria-
hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});

Success message from Bootstrapious contact form appears on a blank page

I'm building a website using Bootstrap and needed a contact form, so I decided to use the one from Bootstrapious. The form works properly and I can receive the messages by email, but the success message appears on a blank page instead of the form page.
I've seen two questions posted here that referred to a similar problem:
PHP contact form redirects to contact.php with success message
- This person resolved the problem himself but doesn't really explain how.
PHP contact form not landing on right page - This one had his problem resolved by someone else, but it doesn't seem to work for me (or maybe I just don't understand the solution given).
Here is my page if you want to try it to see exactly what it does.
And here is the code (I tried to cut the irrelevant parts, but since I don't really know where the problem is, I might have left a little too much).
HTML page:
<!doctype html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap core CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"></head>
<body>
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Prénom*</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Prénom" required="required" data-error="Votre prénom est requis.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Nom de famille*</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Nom de famille" required="required" data-error="Votre nom de famille est requis.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Courriel*</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Courriel" required="required" data-error="Votre adresse courriel est requise.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Téléphone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Numéro de téléphone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_postal">Code postal*</label>
<input id="form_postal" type="text" name="codepostal" class="form-control" placeholder="Code postal" required="required" data-error="Votre code postal est requis." pattern="[A-Za-z][0-9][A-Za-z]\s?[0-9][A-Za-z][0-9]">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message*</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Votre message" rows="4" required="required" data-error="Veuillez entrer votre message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Envoyer">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> Champs obligatoires</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.container -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../../../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
<script src="../../../../assets/js/vendor/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="validator.js"></script>
<script src="contact.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.css"></script>
Contact.php:
<?php
$from = 'test <test#test.com>';
$sendTo = 'test <test#test.com>';
$subject = 'Nouveau message';
$fields = array('name' => 'Prénom', 'surname' => 'Nom de famille', 'phone' => 'Téléphone', 'email' => 'Courriel', 'message' => 'Message');
$okMessage = 'Le formulaire de contact a bien été envoyé. Merci! Nous vous contacterons dans les plus brefs délais.';
$errorMessage = 'Une erreur s\'est produite en envoyant le formulaire. Veuillez réessayer plus tard.';
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Le formulaire est vide');
$emailText = "Vous avez un nouveau message de votre formulaire de contact\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
Contact.js:
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Edit 06/03: I've tried Nitin Sharma's suggestion, but it doesn't work. I can redirect to the first page, but then, the success message doesn't appear at all.
Ondrej from Bootstrapious.com here. I am the author of the tutorial.
The problem was well hidden :) It doesn't work because you work with the Slim version of jQuery which doesn't contain AJAX functions that are needed for this to work.
I hope this helps.
Ondrej
With the action attribute page redirect to any other page. In your condition, it redirects you to contact.php and if you want the page redirect to any other location after submission, just simply change the contact.php to the desired page name.
<form id="contact-form" method="post" action="contact.php" role="form">
change the action to
<form id="contact-form" method="post" action="newPage.php" role="form">

How to display success popup message after clicking on submit button in codeigniter php

Displaying a custom popup message as thank you after clicking on submit button.I have used codeigniter framework.I have a section as request form once the user filled the data and clicked on submit button a pop up message should be displayed on that section as thank you message.Here is my code.
<div class="col-md-3 requestfree">
<img src="<?= base_url(); ?>theme/images/icon1.png" class="requesting">
<h3 class="request">REQUEST</h3>
<h5 class="free"> FREE QUOTE</h5>
<h5 class="receive">You will receive quote within 24 hours</h5>
<form name="contact" id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>welcome/request">
<?php if (isset($msg)): ?>
<?= $msg; ?>
<?php endif; ?>
<div class="name"><span class="mandatory"></span>
<input type="text" class="form-control" name="name" placeholder="Name" required>
<?= form_error('name', '<div class="error">', '</div>'); ?>
</div>
<div class="name">
<input type="text" class="form-control" name="phone" placeholder="Phone" required>
<?= form_error('phone', '<div class="error">', '</div>'); ?>
</div>
<div class="email">
<input type="email" class="form-control" name="email" placeholder="Email" required>
<?= form_error('email', '<div class="error">', '</div>'); ?>
</div>
<div class="description">
<textarea name="description" style="width:100%;overflow:auto;" placeholder="Description" required></textarea>
</div>
<div class="">
<div class="captchas">
<img src="captcha.php?rand=<?= rand(); ?>" class="captchass" id='captchaimg'/>
<p class="change">click to change</p>
</div>
<div class="captcha">
<input type="text" class="form-control"id="captcha_code" name="captcha_code" style="background-color: #EAD5D2;border: none;">
</div>
</div>
<button type="submit" class="btn btn-success" onclick="return validate();">Submit</button>
<p class="privacy">We respect your privacy</p>
</form>
</div>
Controller:
function request()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('name','First Name' , 'required');
$this->form_validation->set_rules('email','Email','required|valid_email');
$this->form_validation->set_rules('phone','Mobile Number','required|numeric');
$this->form_validation->set_rules('description','Description','required');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='index';
$this->load->view('templates/template',$data);
}
else
{
echo "hi";
//get the form data
$name = $this->input->post('name');
$from_email = $this->input->post('email');
$phone = $this->input->post('phone');
$description = $this->input->post('description');
//set to_email id to which you want to receive mails
$to_email = 'gmail#gmail.com';
$config=Array(
'protocol'=> 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com', //smtp host name
'smtp_port' => '465', //smtp port number
'smtp_user' => 'mail#gmail.com',
'smtp_pass' => '*******', //$from_email password
'mailtype' =>'html',
'newline' =>"\r\n",
'crlf' =>"\r\n",
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = array();
$message[] = 'Username : '.trim($name).' ';
$message[] = 'Phone Number : '.trim($phone).' ';
$message[] = 'Description : '.trim($description).' ';
$message = implode(PHP_EOL, $message);
//send mail
$this->load->library('email',$config);
$this->email->from($from_email);
$this->email->to($to_email);
$this->email->subject('Request Free Quote');
$this->email->message($message);
$this->email->set_newline("\r\n");
if ($this->email->send())
{
// mail sent
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
redirect('welcome');
}
else
{
//error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
redirect('welcome');
}
}
}

Php File For HTML Php form

I am studying on a site template for quite long. I have a contact form in my site and my html file (index.html) is linked to a js file (contact-me.js). I'm providing them below :
Contact Form In index.html :
<!-- OPEN - Content -->
<div class="item-title text-center">
<!-- Contact form -->
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Write your name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Write your email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your email address'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area" required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message</button>
</form>
<!-- /. Contact form -->
<div id="block-answer">
<div id="answer"></div>
</div>
</div> <!-- CLOSE - Content -->
and my contact-me.js is :
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userSubject':user_subject, 'userMessage':user_message};
// Ajax post data to server
$.post('php/contact-me.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
output = '<div class="error-message"><p>'+response.text+'</p></div>';
} else {
output = '<div class="success-message"><p>'+response.text+'</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
Can You Please Help Me With The php file. I am completely new to php. Please help me with the php file that I should use for this form.
Here is a sample code.
You need a basic understanding of POST and GET method and read the PHP manual on how to use 'mail()'
<?php
$to = "mail#yourdomain.com";
$from = $_POST['user_email'];
$name = $_POST['user_name'];
$headers = "From: $from";
$subject = $_POST['user_subject'];
$body = $_POST['user_message'];
$send = mail($to, $subject, $body, $headers);
?>
I assumed that you need a php script to send you the data on your mail that user enters
I seriously have no idea why you are using Javascript(you are not verifying data,so use post action method of php. just add action="somename.php" in form tag,somewat like this
<form id="contact-form" name="contact-form" method="POST" action="somename.php">
and in somename.php keep the following content
<?php
$name = $_POST['name'];
$usermail = $_POST['email-address'];
$message = $_POST['message'];
$to = "yourmail#example.com";
$subject = $_POST['subject'];
$text = "Name-" . $name ."\nEmail-" . $usermail ."\nMessage-" . $message;
$headers = "From: webmaster#yourdomain.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$text,$headers);
?>
You may continue using javascript(if so dont add action to form tag).

ng-select just return the word 'array"

i have a ng-select in a contact form, I recieve correctly the form except ng-select.
The system just return me the word "array", but I need the selected option from the ng-select.
This is my portion of html
<div ng-controller="ContactController" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="row half" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<div class="12u">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Nombre" required>
</div>
</div>
<div class="row half" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<div class="12u">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email de contacto" required>
</div>
</div>
<!-- select -->
<div class="row half" ng-class="{ 'has-error': contactform.myDepartment.$invalid && submitted }">
<div class="12u">
<select ng-model="formData.myDepartment" ng-options="departamento.name for departamento in departamento" id="myDepartment" name="myDepartment">
<option value="">-- Tipo de mensaje --</option>
</select>
</div>
</div>
<!-- select -->
<div class="row half" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<div class="12u">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Asunto del mensaje" required>
</div>
</div>
<div class="row half" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<div class="12u">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Mensaje" required></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<input type="submit" name="submit" id="submit_btn" value="Enviar mensaje" ng-disabled="submitButtonDisabled"/>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
This is the code of controller.js
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.departamento = [
{name:'Selecciona departamento'},
{name:'RRHH'},
{name:'Soporte'},
{name:'Postventa'},
{name:'Comercial'},
{name:'Desarrollo'}
];
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : '/contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
$scope.myDepartment = $scope.departamento.name; // red
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed :( Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
And this is the Php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['myDepartment']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['myDepartment']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Completa el formulario antes de enviar');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('xxxx#xxx.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nDepartment: " . $_POST['myDepartment'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'El mensaje no puede ser enviado. Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Gracias, hemos recibido tu mensaje.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Rellena el formulario completamente.');
echo json_encode($data);
}
Can you help me?
Thanks, Luiggi
You are having the entire object be set for $scope.myDepartment. Instead of
ng-options="departamento.name for departamento in departamento"
try using
ng-options="departamento.name as departamento.name for departamento in departamento"
this should set $scope.myDepartment to the actual string selected, rather than an object of {name: selection}
Firstly, your ng-options syntax is wrong. It should be
ng-options="singular.title for singular in plural"
If you had an array of objects like this:
$scope.departamento = [{name: dep1}, {name: dep2}]
You would write ng-options like this:
ng-options="d.name for d in departamento"
Where d is any variable name.
Also I don't think you should be doing this
data : $.param($scope.formData)
Because $scope.formData is already a javascript object, and $http, unlike $.ajax automatically stringify's your objects.

Categories

Resources