I can send email and get normally , but would like to click the submit button , the form was sent and presented a message to the user and continue on the page normally ... Ja tried with ajax and everything and nothing.
I would like the message to appear in a div , identical to the image below.
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'];
}
?>
...
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
...
You're not preventing the default action.
You probably want to use:
...
$('#contact_form').on('submit', function (e) {
// Prevent form submission
e.preventDefault();
if (true) { // you no longer need the if-block
...
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));
?>
Related
PHP Script & Validation:
function SampleInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['RegisterClient'])) {
$file = $_FILES['avatar']['name'];
$file_location = $_FILES['avatar']['tmp_name'];
$folder = "../Public/img/uploads/profile-picture/";
$new_file_name = strtolower($file);
$final_file = str_replace(' ', '-', $new_file_name);
$name = htmlspecialchars(trim($_POST['name'], ENT_QUOTES));
$username = htmlspecialchars(trim($_POST['username'], ENT_QUOTES));
$email = htmlspecialchars(trim($_POST['email'], ENT_QUOTES));
$password = htmlspecialchars(trim($_POST['password'], ENT_QUOTES));
$cpassword = htmlspecialchars(trim($_POST['cpassword'], ENT_QUOTES));
$role = htmlspecialchars(trim($_POST['role'], ENT_QUOTES));
if (move_uploaded_file($file_location, $folder.$final_file)) {
$image = $final_file;
}
if(empty($_POST['name']) || empty($_POST['username']) || empty($_POST['password']) || empty($_POST['cpassword']) || empty($_POST['role'])) {
$error = "All fields are required!";
} else {
$name = SampleInput($_POST['name']);
$username = SampleInput($_POST['username']);
$password = SampleInput($_POST['password']);
$cpassword =SampleInput($_POST['cpassword']);
$role = SampleInput($_POST['role']);
if (!preg_match('/^[a-zA-Z0-9\s]+$/',$name && $username && $password && $cpassword && $role)) {
$error = "Only letters and white space allowed";
}
}
$stmt = $db->prepare("INSERT INTO clients(name, username, email, password, avatar, role, registration_date) VALUES (:name, :username, :email, :password, :avatar, :role, NOW())");
$stmt->execute(array(
'name' => $name,
'username' => $username,
'email' => $email,
'password' => $password,
'avatar' => $image,
'role' => $role
));
$success = 'Registered!';
}
Modal:
<div class="modal fade" id="add" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form action="" method="POST" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create user</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
if ($error) {
echo '<div class="mb-3">' . $error . '</div>';
} else if ($success) {
echo '<div class="mb-3">' . $success . '</div>';
}
?>
<div class="row gx-3 mb-3">
<div class="col-md-12">
<label class="small mb-1" for="login-fullname">Full name*</label>
<input class="form-control" name="name" type="text" placeholder="Valid full name" />
</div>
</div>
<div class="mb-3">
<label class="small mb-1" for="login-username">Username (how your name will appear to other users on the site)</label>
<input class="form-control" name="username" type="text" placeholder="Valid username" />
</div>
<div class="mb-3">
<label class="small mb-1" for="login-email">Email address</label>
<input class="form-control" name="email" type="text" placeholder="Valid email" />
</div>
<div class="row gx-3 mb-3">
<div class="col-md-6">
<label class="small mb-1" for="login-password">Password</label>
<input class="form-control" name="password" type="password" placeholder="Strong password" />
</div>
<div class="col-md-6">
<label class="small mb-1" for="login-cpassword">Confirm Password</label>
<input class="form-control" name="cpassword" type="password" placeholder="Strong password" />
</div>
</div>
<div class="row gx-3 mb-3">
<div class="card-body text-center">
<input type="file" required class="btn btn-primary" name="avatar">
<div class="small font-italic text-muted mb-6">JPG or PNG no larger than 5 MB</div>
</div>
</div>
<div class="mb-3">
<label class="small mb-1" for="selectRole">Select user role</label>
<select class="form-control" name="role">
<option value="">Select user role</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
<button type="submit" name="RegisterClient" class="btn btn-primary">Create</button>
</div>
</div>
</form>
</div>
</div>
I don't know where the problem is, I want the modal to remain open even if the problem or form has been submitted successfully. Now, with this code, if there is a problem with the submit form, the modal shuts down and if we open it again, the user can see error messages. Where am I wrong?
After a whole day, I resolve an issue with this.
$('#myModal').modal({
backdrop: 'static',
keyboard: false
})
With this code written above, a modal will be closed only if the user clicks on the close button. With this code, you disabled the close modal by pressing the ESC button on the keyboard.
I'm a beginner in Laravel and I'm trying to create a form and submit it to the database.
I managed to save the data to the database using the following code.
My blade:
<form id="castingform" method="post" action="castingss" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" id="id_hidden" name="id" />
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_cin">CIN</label>
<input type="text" class="form-control" id="casting_cin" name="casting_cin" placeholder="Cin">
<span class="text-danger">{{ $errors->first('casting_cin') }}</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_email">Email</label>
<input type="text" class="form-control" id="casting_email" name="casting_email" placeholder="Email">
<span class="text-danger">{{ $errors->first('casting_email') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_phone">Téléphone</label>
<input type="tel" class="form-control" id="casting_phone" name="casting_phone" placeholder="Téléphone">
<span class="text-danger">{{ $errors->first('casting_phone') }}</span>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_age">Age</label>
<input type="number" class="form-control" id="casting_age" name="casting_age" placeholder="Age">
<span class="text-danger">{{ $errors->first('casting_age') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_sexe">Sexe</label>
<div class="custom-control custom-radio">
<input type="radio" name="casting_sexe" id="casting_sexeh" class="custom-control-input" value="homme">
<label class="custom-control-label" for="casting_sexeh">Homme</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" name="casting_sexe" id="casting_sexef" class="custom-control-input" value="femme">
<label class="custom-control-label" for="casting_sexef" >Femme</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="casting_city">City</label>
<input type="text" class="form-control" name="casting_city" id="casting_city">
<span class="text-danger">{{ $errors->first('casting_city') }}</span>
</div>
<div class="form-group col-md-6">
<label for="casting_address">Address 2</label>
<input type="text" class="form-control" id="casting_address" name="casting_address" >
<span class="text-danger">{{ $errors->first('casting_address') }}</span>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<div class=" col-md-6">
<span id="store_image" text-align: center></span>
</div>
</br> </br> </br> </br> </br>
<span class="result"></span>
<div class="form-group" align="center">
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="ADD" />
</div>
<div class=" col-md-6">
<span id="form_result"></span>
</div>
</form>
<!--------------------- script---------------------
<script type="text/javascript">
$(document).ready(function(){
$('#castingform').on('submit', function(event){
event.preventDefault();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('castingss.store') }}",
method:"POST",
data: new FormData(this),
dataSrc: "",
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
alert('je suis là');
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#sample_form')[0].reset();
$('#datatableRows').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
})
}
});
});
</script>
My controller:
public function store(Request $request)
{
$rules = array(
'casting_name' => 'required',
'casting_cin' => 'required|max:8|unique:castings',
'casting_email' => 'required|email|unique:castings',
'casting_phone' => 'required',
'casting_age' => 'required',
'casting_sexe' => 'required',
'casting_city' => 'required',
'casting_address' => 'required',
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors' => $error->errors()->all()]);
}
$image = $request->file('casting_photo');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('castingimages'), $new_name);
$form_data = array(
'casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo' => $new_name
);
Casting::create($form_data);
return response()->json(['success' => 'Data Added successfully.']);
}
All works very well for me, but now I wanted to add something else to my form.
I wanted based on the value of the input age to display other inputs.
This means if the age is less than 18, two other inputs, one for the name of the guarantor and the other for the identification number of the guarantor, had to be displayed and the age was recorded in the database with the name and the identifier of the guarantor and if the age is over 18 years old we do nothing we record the data in the database with the age of 18 years old.
How could I do this? If you have an idea please give me the lead to follow to achieve this.
EDIT
<script type="text/javascript">
$(document).ready(function(){
$('#castingform').on('submit', function(event){
event.preventDefault();
var castingAgeInput = document.getElementById('casting_age');
var guarantorContainer = document.querySelector('.js-guarantor-container');
var guarantorIdentificationNumberContainer = document.querySelector('.js-guarantor_identification_number-container');
castingAgeInput.addEventListener('change', function(evt) {
if (+evt.target.value < 18) {
guarantorContainer.removeAttribute('hidden');
guarantorIdentificationNumberContainer.removeAttribute('hidden');
} else {
guarantorContainer.setAttribute('hidden', true);
guarantorIdentificationNumberContainer.setAttribute('hidden', true);
}
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('castingss.store') }}",
method:"POST",
data: new FormData(this),
dataSrc: "",
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<div class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
alert('je suis là');
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#sample_form')[0].reset();
$('#datatableRows').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
})
}
});
});
</script>
But it doesn't work
You can just add these fields hidden and toggle their visibility:
var castingAgeInput = document.getElementById('casting_age');
var guarantorContainer = document.querySelector('.js-guarantor-container');
var guarantorIdentificationNumberContainer = document.querySelector('.js-guarantor_identification_number-container');
castingAgeInput.addEventListener('change', function(evt) {
if (+evt.target.value < 18) {
guarantorContainer.removeAttribute('hidden');
guarantorIdentificationNumberContainer.removeAttribute('hidden');
} else {
guarantorContainer.setAttribute('hidden', true);
guarantorIdentificationNumberContainer.setAttribute('hidden', true);
}
});
<div class="form-group col-md-6">
<label for="casting_age">Age</label>
<input type="number" class="form-control" id="casting_age" name="casting_age" placeholder="Age">
<span class="text-danger">{{ $errors->first('casting_age') }}</span>
</div>
<div class="form-group col-md-6 js-guarantor-container" hidden>
<label for="guarantor">Guarantor</label>
<input type="number" class="form-control" id="guarantor" name="guarantor" placeholder="Guarantor">
<span class="text-danger">{{ $errors->first('guarantor') }}</span>
</div>
<div class="form-group col-md-6 js-guarantor_identification_number-container" hidden>
<label for="guarantor_identification_number">Guarantor identification number</label>
<input type="number" class="form-control" id="guarantor_identification_number" name="guarantor_identification_number" placeholder="Age">
<span class="text-danger">{{ $errors->first('guarantor_identification_number') }}</span>
</div>
I have created a form based on the bootstrapious.com contact form tutorial. In my case I have changed it to populate a mysql database. Filling out the form and submitting it does get the information correctly in the database, but does not return a 'success' message or reset the form. I think the problem is in my javascript but am not sure. I would appreciate any help. Thanks
Here is my html
<!DOCTYPE html>
<html>
<head>
<title>Family Member</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<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-lg-8 col-lg-offset-2">
<h1>Family Member Form</h1>
<p class="lead">Please enter your information on the form below</p>
<form id="familyMember-form" method="post" action="familyMember.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_firstname">Firstname *</label>
<input id="form_firstname" type="text" name="firstName" 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="lastName" 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_cellPhone">Cell Phone</label>
<input id="form_cellPhone" type="tel" name="cellPhone" class="form-control" placeholder="Please enter your cell phone number">
<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_password">Password*</label>
<input id="form_password" type="password" name="password" class="form-control" placeholder="Please enter your password*">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_passwordConfirmation">Confirm Password*</label>
<input id="form_passwordConfirmation" type="password" name="passwordConfirmation" class="form-control" placeholder="Please confirm your password*">
<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_familyCode">Family Code *</label>
<input id="form_familyCode" name="familyCode" class="form-control" placeholder="Please Enter Family Code *" rows="4" required="required" data-error="Please,leave us a message.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p></p>
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="validator.js"></script>
<script src="familyMember.js"></script>
</body>
</html>
Here is my php
$okMessage = 'Family member has successfully added.';
$errorMessage = 'there was an error';
try
{
$pdo = new PDO('mysql:host=localhost; dbname=mydb', "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server:' . $e->getMessage();
include 'output.html.php';
exit();
}
//$output = 'Database connection established.';
//include 'output.html.php';
$firstName = $_POST['firstName'];
//echo $firstName;
//echo '<br>';
$lastName = $_POST['lastName'];
//echo $lastName;
//echo '<br>';
$email = $_POST['email'];
//echo $email;
//echo '<br>';
$cellPhone = $_POST['cellPhone'];
//echo $cellPhone;
//echo '<br>';
$password = $_POST['password'];
//echo $password;
//echo '<br>';
$familyCode = $_POST['familyCode'];
//echo $familyCode;
//echo '<br>';
try{
$sql = 'INSERT INTO familyMembers(FirstName, LastName, Email, Password, cell_phone, familyCode)
Values(:FirstName, :LastName, :Email, :Password, :cell_phone, :familyCode)';
$statement = $pdo -> prepare($sql);
$statement -> execute(array(':FirstName' => $firstName, ':LastName' =>$lastName, ':Email'=> $email, ':Password'=> $password, ':cell_phone' => $cellPhone, ':familyCode' => $familyCode));
$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'];
}
Here is my javascript
$(function () {
$('#familyMember-form').validator();
$('#familyMember-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "familyMember.php";
alert(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
alert(url);
alert(data);
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
alert(messageAlert);
alert(messageText);
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) {
$('#familyMember-form').find('.messages').html(alertBox);
$('#familyMember-form')[0].reset();
}
}
});
return false;
}
});
});
I was trying to create a signup form where a user has to give his data along with the image. I have attached the snippet of the code I was trying but couldn't achieve please help me. I have already been through other similar question but none of them helped me.
function submitForm1()
{
var data = $("#signup").serialize();
$.ajax({
type : 'POST',
url : 'signup_process.php',
data : data,
async: false,
beforeSend: function()
{
$("#error1").fadeOut();
$("#btn-signup").html('<span class="glyphicon glyphicon-transfer"></span> Signing Up..Please wait.');
},
success : function(response)
{
if(response=="ok"){
$("#error1").fadeIn(1000, function(){
$("#error1").html('<div class="alert alert-success"> <span class="glyphicon glyphicon-info-sign"></span> An Email has been sent to your entered email address. Please follow the instruction to activate your account.</div>');
$("#btn-signup").html('<span class="glyphicon glyphicon-transfer"></span> Sign Up');
});
}
else{
$("#error1").fadeIn(1000, function(){
$("#error1").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
$("#btn-signup").html('<span class="glyphicon glyphicon-log-in"></span> Sign In');
});
}
}
cache: false,
contentType: false, //must, tell jQuery not to process the data
processData: false,
});
return false;
}
/* login submit */
});
<div class="container">
<div class="signup-form-container">
<form id="signup" name="form1">
<div class="head"></div>
<div class="form-header" style="text-align:center;">
<div class="image" id="preview">
<div id="timelineShade" style="background:url(assets/pic.png) center;"></div>
</div>
<h3 class="form-title" style="margin-top:-60px;"><span style="margin-right:50px;"></span>Recruiter Sign-up Portal</h3>
</div>
<div class="form-body">
<!-- json response will be here -->
<div id="error1"></div>
<!-- json response will be here -->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
<input type="text" name="name" class="form-control" placeholder="Full Name" id="name" /> </div>
<span class="help-block" id="error"></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></div>
<input type="text" name="email" class="form-control" placeholder="Email" id="email" /> </div>
<span class="help-block" id="error"></span>
</div>
<div class="row">
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input type="password" name="password" id="password" class="form-control"placeholder="Password" /> </div>
<span class="help-block" id="error"></span>
</div>
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input type="password" name="cpassword" class="form-control" placeholder="Confirm Password"/> </div>
<span class="help-block" id="error"></span>
</div>
</div>
<div class="form-group col-lg-6" style="max-width:145px; margin-top:10px;">
<div class="input-group">
<label>Company Logo</label>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input id="imagein" name="image" type="file" class="form-control" limit=1/>
</div>
<span class="help-block" id="error"></span>
</div>
</div>
<div class="form-footer">
<button type="submit" name="btn-signup" id="btn-signup" class="btn bt-login" style="margin-left:8%; width:92%" >Sign-up <span class="glyphicon glyphicon-log-in"></span> </button>
</div>
<div class="form-footer"> <div class="col-xs-4 col-sm-4 col-md-4" style="margin-left:0%; float:left;">
<i class="fa fa-lock"></i>
Forgot password? </div>
<div class="col-xs-4 col-sm-4 col-md-4" style="margin-left:0%; float:right;">
<i class="fa fa-user"></i>
Log-In </div>
</div>
</form>
</div>
</div>
<?php
session_start();
$upload_dir = '/upload/'; // upload directory
error_reporting(0);
require_once 'class.user.php';
$reg_user = new USER();
if($reg_user->is_logged_in()!="")
{$reg_user->redirect('home.php');}if(isset($_POST['btn-signup'])){
$phone = trim($_POST['phone']);$email = trim($_POST['email']);
$upass = trim($_POST['password']);$code = md5(uniqid(rand()));
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions)){if($imgSize < 5000000){
move_uploaded_file($tmp_dir,$upload_dir.$userpic);}else{
$errMSG = "Sorry, your file is too large.";}}else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";}
if($reg_user->register($phone,$email,$upass,$code,$userpic)){
$id = $reg_user->lasdID();$key = base64_encode($id);$id = $key;
$message = "Hello $email,<br /><br />
Welcome to Coding Cage!To complete your registration please , just
clickfollowing link<br/><br /><br /><a href='http://localhost/x/verify.php?
id=$id&code=$code'>Click HERE to Activate :)</a><br /><br />Thanks,";
$subject = "Confirm Registration";require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();$mail->IsSMTP(); $mail->SMTPDebug = 0;
$mail->SMTPAuth = true; $mail->SMTPSecure = "ssl";
$mail->Host= "smtp.gmail.com"; $mail->Port= 465;
$mail->AddAddress($email);
$mail->Username="sharma.himanshu0405#gmail.com";
$mail->Password="mypassword";
$mail->SetFrom('sharma.himanshu0405#gmail.com','Himanshu');
$mail->Subject = $subject;
$mail->Subject = $subject; $mail->MsgHTML($message);
if($mail->send()) { echo "ok" ; } else {
echo "Sorry, Registration is not possible this time. Please try again after some time or Contact Admin";
$stmt = $reg_user->runQuery("DELETE FROM tbl_users WHERE user_email=:email_id");
$stmt->execute(array(":email_id"=>$email));
}
}
}
?>
Have to encode the image in the form to base64 (not sure) before providing serialized form data in ajax call
I have problem with ajax modal on my codeigniter project. I don't know why the submit button didn't work. the modal can be shown, but when I click the save button, nothing happens.
this is my javascript :
<script type="text/javascript" src="<?php echo site_url('assets/js/jquery.js'); ?>"></script>
<script src="<?php echo site_url('assets/js/bootstrap.min.js');?>"> </script>
<script type="text/javascript">
$('#submit').click(function() {
var form_data = {
name: $('#nama').val(),
email: $('#email').val(),
};
$.ajax({
url: "<?php echo site_url('adminproses/update'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 'YES')
$('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
else if (msg == 'NO')
$('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
return false;
});
});
this my modal form :
<div class="modal fade" id="edit-modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Detail Data Anda</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_user"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Nomor Induk Pegawai</label>
<div class="col-md-9">
<input name="NIP" placeholder="Nomor Induk Pegawai" id="NIP" class="form-control" type="text" value="<?php echo $tampil['NIP'];?> ">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nama</label>
<div class="col-md-9">
<input name="nama" placeholder="Nama Lengkap Anda" id="nama" class="form-control" type="text" value="<?php echo $tampil['nama'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Alamat</label>
<div class="col-md-9">
<textarea name="alamat" id="alamat" placeholder="Jalan A Nomor 1, Kelurahan A, Desa A, Kecamatan A, Kabupaten A, Provinsi A." class="form-control" ><?php echo $tampil['alamat'];?></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nomor HP</label>
<div class="col-md-9">
<input name="no_hp" placeholder="081111111111" id="no_hp" class="form-control" type="text" value="<?php echo $tampil['no_hp'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">E-mail</label>
<div class="col-md-9">
<input name="email" placeholder="email#service.com" id="email" class="form-control" type="text" value="<?php echo $tampil['email'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Kategori</label>
<div class="col-md-9">
<select name="id_katuser" class="form-control" id="kategori">
<option value="">Pilih Kategori</option>
<?php foreach ($katuser as $kat){?>
<option value="<?php echo $kat['id_katuser']; ?>" <?php if($kat['id_katuser']==$tampil['id_katuser']){echo "selected";}?>>
<?php echo $kat['nama_katuser']; ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Username</label>
<div class="col-md-9">
<input name="username" placeholder="Username" id="username" class="form-control" type="text" value="<?php echo $tampil['username'];?>">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Password</label>
<div class="col-md-9">
<input name="password" placeholder="Password" id="password" class="form-control" type="text" value="<?php echo $tampil['password'];?>">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div id="alert-msg"></div>
<div class="modal-footer">
<button type="button" id="btnSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
and the controller :
public function update(){
//set validation rules
$this->form_validation->set_rules('NIP', 'nip', 'trim|required|xss_clean');
$this->form_validation->set_rules('nama', 'email', 'trim|required|xss_clean');
$this->form_validation->set_rules('alamat', 'alamat', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Emaid ID', 'trim|required|valid_email');
$this->form_validation->set_rules('no_hp', 'no_hp', 'trim|required|xss_clean');
$this->form_validation->set_rules('kategori', 'kategori', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
//run validation check
if ($this->form_validation->run() == FALSE){
//validation fails
echo validation_errors();
}
else{
//get the form data
$NIP = $this->input->post('NIP');
$nama = $this->input->post('nama');
$alamat = $this->input->post('alamat');
$no_hp = $this->input->post('no_hp');
$email = $this->input->post('email');
$id_katuser = $this->input->post('kategori');
$username = $this->input->post('username');
$password = $this->input->post('password');
}
}
Thank you for the help.
Use this to post the data
$('#btnSave').click(function(e) {
e.preventDefault();
var form_data = {
name: $('#nama').val(),
email: $('#email').val()
};
$.ajax({
url: '<?php echo site_url('adminproses/update'); ?>',
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 'YES')
$('#alert-msg').html('<div class="alert alert-success text-center">Your mail has been sent successfully!</div>');
else if (msg == 'NO')
$('#alert-msg').html('<div class="alert alert-danger text-center">Error in sending your message! Please try again later.</div>');
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
return false;
});
});