我可以发送电子邮件并获得正常,但是想要点击提交按钮,表单已发送并向用户显示消息并正常继续在页面上... Ja尝试使用ajax和所有内容。< / p>
我希望消息显示在div中,与下图相同。
HTML
<form class="well form-horizontal" action="php/contato.php" method="post" id="contact_form">
<fieldset>
<legend style="text-align: center;">Fale conosco</legend>
<!-- Nome -->
<div class="form-group">
<label class="col-md-4 control-label">Nome</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Nome Completo" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Email-->
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Telefone-->
<div class="form-group">
<label class="col-md-4 control-label">Telefones</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br>
<input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text">
</div>
</div>
</div>
<!-- Assunto-->
<div class="form-group">
<label class="col-md-4 control-label">Assunto</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span>
<input name="assunto" placeholder="Assunto" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Mensagem -->
<div class="form-group">
<label class="col-md-4 control-label">Deixe-nos sua mensagem.</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea>
</div>
</div>
</div>
**<!-- I want the message to appear here -->**
<div class="alert alert-success" role="alert" id="success_message">Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve.</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning">Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
的JavaScript
$(function () {
$('#contact_form').validator();
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "php/contato.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact_form').find('.messages').html(alertBox);
$('#contact_form')[0].reset();
}
}
});
return false;
}
})
});
contato.php
<?php
// configure
$from = 'email';
$sendTo = 'email';
$subject = 'Contato do site';
$fields = array('name' => 'Nome do Cliente', 'email' => 'Email', 'telefone' => 'Telefone', 'celular' => 'Celular', 'assunto' => 'Assunto', 'mensagem' => 'Mensagem'); // array variable name => Text to appear in email
$okMessage = 'Email enviado, já já entraremos em contato';
$errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor';
// let's do the sending
try
{
$emailText = "Mais um contato chegando através do site\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
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 {
echo $responseArray['message'];
}
?>
答案 0 :(得分:2)
class AlbumsController < ApplicationController
before_action :valid_user, only: [:new, :create, :edit, :update, :destroy]
def create
@album = current_user.albums.build(album_params)
if params[:images]
params[:images].each { |file|
debugger #file.class is String in integration test
@album.pictures.build(image: file)
}
end
if @album.save
# end
flash[:success] = "Album Created!"
redirect_to current_user
else
flash[:alert] = "Something went wrong."
render :new
end
end
private
def album_params
params.require(:album).permit(:user_id, :title, :description, :price,
pictures_attributes: [:id, :image, :image_cache, :_destroy])
end
def valid_user
@user = User.friendly.find(params[:user_id])
redirect_to(root_url) unless @user == current_user
end
end
您没有阻止默认操作。
您可能想要使用:
...
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
...
答案 1 :(得分:1)
<强> HTML 强>
<form class="well form-horizontal" action="" method="POST" id="contact_form">
<fieldset>
<legend style="text-align: center;">Fale conosco</legend>
<!-- Nome -->
<div class="form-group">
<label class="col-md-4 control-label">Nome</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Nome Completo" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Email-->
<div class="form-group">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Telefone-->
<div class="form-group">
<label class="col-md-4 control-label">Telefones</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br>
<input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text">
</div>
</div>
</div>
<!-- Assunto-->
<div class="form-group">
<label class="col-md-4 control-label">Assunto</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span>
<input name="assunto" placeholder="Assunto" class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Mensagem -->
<div class="form-group">
<label class="col-md-4 control-label">Deixe-nos sua mensagem.</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea>
</div>
</div>
</div>
<!-- I want the message to appear here -->
<div class="alert alert-success" role="alert" id="success_message">
Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve.
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<button type="submit" class="btn btn-warning">Enviar <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
JAVASCRIPT
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
(function ($) {
$(document).ready(function (e) {
var contactForm = $('#contact_form');
contactForm.on('submit', function (evt) {
evt.preventDefault();
var url = "contato.php";
var objData = {
"name" : $("input[name=name]").val(),
"email" : $("input[name=email]").val(),
"telefone" : $("input[name=telefone]").val(),
"celular" : $("input[name=celular]").val(),
"assunto" : $("input[name=assunto]").val(),
"mensagem" : $("input[name=mensagem]").val()
};
$.ajax({
type: "POST",
url: url,
data: objData,
success: function (data){
if (data.type && data.message) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">';
alertBox += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
alertBox += messageText + '</div>';
contactForm.find('#success_message').html(alertBox);
contactForm[0].reset();
}
}
});
return false;
})
});
})(jQuery);
</script>
<强> PHP 强>
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
// PLEASE MAKE SURE YOU DON'T HAVE ANY WHITESPACE BEFORE THE OPENING PHP TAG (<?php)
// Por favor, certifique-se de que você não tem qualquer espaço em branco antes da tag de abertura do PHP ( <?php )
$from = 'email';
$sendTo = 'email';
$subject = 'Contato do site';
$okMessage = 'Email enviado, já já entraremos em contato';
$errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor';
try {
// GET & SANITIZE THE POST DATA...
$name = isset($_POST['name']) ? htmlspecialchars(trim($_POST['name'])) : "";
$email = isset($_POST['email']) ? htmlspecialchars(trim($_POST['email'])) : "";
$telefone = isset($_POST['telefone']) ? htmlspecialchars(trim($_POST['telefone'])) : "";
$celular = isset($_POST['celular']) ? htmlspecialchars(trim($_POST['celular'])) : "";
$assunto = isset($_POST['assunto']) ? htmlspecialchars(trim($_POST['assunto'])) : "";
$mensagem = isset($_POST['mensagem']) ? htmlspecialchars(trim($_POST['mensagem'])) : "";
// BUILD UP THE MESSAGE...
$emailText = "Mais um contato chegando através do site\n=============================\n";
$emailText .= "Nome do Cliente: \n$name\n\n";
$emailText .= "Email: \n$email\n\n";
$emailText .= "Telefone: \n$telefone\n\n";
$emailText .= "Celular: \n$celular\n\n";
$emailText .= "Assunto: \n$assunto\n\n";
$emailText .= "Mensagem: \n$mensagem\n\n";
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// SIMPLY DIE-OUT THE JSON-ENCODED RESPONSE...
die(json_encode($responseArray));
?>