Contact form shows confirmation on new page instead in div (ajax) - javascript

I'm trying to get that Contact Form to Work:
https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
but the confirmation Text opens in a new site instead of the div "messages".
contact.php
<form id="contact-form" method="post" action="contactaction.php" role="form" data-toggle="validator">
<div class="messages"></div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
<script src="contact.js"></script>
contact.js
$(function () {
// init the 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;
}
})
});

Just use e.preventDefault(); as the first step of the onsubmit function:
// when the form is submitted
$(function () {
// init the validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
e.preventDefault();
// if the validator does not prevent form submit
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;
})
});

Related

Highlight and append msg to element on return from .ajax

Upon ajax successful return, the return data contains status. if status is false(not ajax fail), return data contains array of element names and associated error message. The goal is to replicate .validate() error functionality by appending msg after element and highlight.
HTML form:
<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
<div class="form-group">
<div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
<label for="crntPwd">Existing Password:</label>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
<input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
</div>
</div>
.
. more HTML follows
.
JQUERY:
.
.yada, yada, yada
.
$("#chngPwdForm").submit(function(event){
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $("#chngPwdForm").attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var element;
var errorObj = new Error("");
$.each(data.Msg, function(elemName, errMsg) {
element = $("#chngPwdForm").filter("#" + elemName);
errorObj.message = errMsg;
$(element).closest(".form-group").addClass("has-error");
errorObj.insertAfter(element);
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
.fail (function(response){
var Msg = "chngPwd call failed. errorThrown: " + response;
var obj = JSON.stringify(response);
alert("obj is: " + obj);
$('#chngPwdForm div[id="errorTxt"]').text(Msg);
})
}
else {
$('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
}
return false;
The JSON response from changepwd.php:
{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or #\"}
JS error
"TypeError: errorObj.insertAfter is not a function" is thrown for
"errorObj.insertAfter(element);"
The implemented solution:
JQuery:
// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
*$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $(this).attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var focusSet = false;
$.each(data.Msg, function(elemName, errMsg) {
*$("#" + elemName).attr("type", "text");
if (!$("#" + elemName).parent().hasClass("error")) {
$("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>');
}
if (!focusSet) {
$("#" + elemName).focus();
focusSet = true;
}*
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})

My site does not open, stays on the white screen, raises "Object doesn't support property or method 'validator'" error

That's error ; When I followed the console screen while the page was loading it gave the error "SCRIPT438: SCRIPT438: Object doesn't support property or method 'validator'". It is showing the error in the contact.js file.
I could not solve the problem. Can you help me ?
My code in contact.js :
$(function () {
$('.contact-form').validator();
$('.contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "vendor/contact/contact.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">' + messageText + '</div>';
if (messageAlert && messageText) {
$('.contact-form').find('.messages').html(alertBox);
$('.contact-form')[0].reset();
}
}
});
return false;
}
})
});
There's no such method called 'validator'.
Assuming you're using the typical jquery validator plugin, what you're looking for is just 'validate()'

json_encode with log information placed in from of the real data

I use ajax to sent data (a form form html) to php, php would process the data and return result from php to ajax again. I checked php did its job. And php also gets the right result.
$responseArray = array("type" => "success", "message" => $okMessage);
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
header('Content-Type: application/json; charset=utf8', true);
$encoded = json_encode($responseArray);
echo $encoded;
}
and the following code is really called,
But the data ajax received is
2017-10-05 23:18:04 CLIENT -> SERVER: EHLO localhost
2017-10-05 23:18:04 SERVER -> CLIENT: 250-smtp.gmail.com at your service, bla...bla...
{"type":"success","message":"Contact form successfully submitted. Thank you, I will get back to you soon!"}
In this case I only need the last line. I tried to stop it to print the log information. One solution is to change /etc/php.ini. But I do not have this file.
Here is the .js code clip.
$.ajax({
type: "POST",
url: url,
// dataType:"json", /*can not get data back from php but the output of php is right */
data: $(this).serialize(),
success: function(data) {
// 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>';
$('#main-contact-form').find('.messages').html(alertBox);
// empty the form
$('#main-contact-form')[0].reset();
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#main-contact-form').find('.messages').html(alertBox);
// empty the form
$('#main-contact-form')[0].reset();
}
}
});
php file
hide the header function (not mandatory) //header('Content-Type: application/json; charset=utf8', true); the json encoded is correct.
$responseArray = array("type" => "success", "message" => $okMessage);
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//header('Content-Type: application/json; charset=utf8', true);
$encoded = json_encode($responseArray);
echo $encoded;
}
.js code
datatype added json and used data['type'] and data['message']
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $(this).serialize(),
success: function(data) {
// 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>';
$('#main-contact-form').find('.messages').html(alertBox);
// empty the form
$('#main-contact-form')[0].reset();
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#main-contact-form').find('.messages').html(alertBox);
// empty the form
$('#main-contact-form')[0].reset();
}
}
});
Note: I didnt tested the above code.

JQuery .find and .html(alertBox) not working with Bootstrap

I have an AJAX contact form with Bootstrap theme.
Here I have to tried to add alert box like this
$('#contact-form').find('.sashikanta').html(alertBox);
But the selector cannot able to find the class .sashikanta. In the place of the above simple alert is working fine and the email form working.
Below is my JS code.
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "mail.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('.sashikanta').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
Please suggest I did not find anything through Firebug.

Show wait div until server response in ajaxForm

<script type="text/javascript">
$(document).ready(function (event) {
$('#reset_btn').click(function () {
$("#Sender").val("");
$("#message").val("")
});
$('#form1').ajaxForm({
dataType: 'json',
success: function (response) {
var user_phone = $('<?php echo $type;?>[name=Sender]').val();
var user_message = $('textarea[name=message]').val();
var proceed = true;
if (user_phone == "") {
$('<?php echo $type;?>[name=Sender]').addClass('inp-form-error');
proceed = false;
}
if (user_message == "") {
$('textarea[name=message]').addClass('form-textarea-red');
proceed = false;
}
if (proceed) {
$("#wait").show();
if (response.type == 'error') {
output = '<div id="msg_1" class="error_msg_003"><div id="image" class="msg_003_image"></div>' + response.text + '</div>'
} else if (response.type == 'warning') {
output = '<div id="msg_1" class="warning_msg_003"><div id="image" class="msg_003_image"></div>' + response.text + '</div>'
} else {
output = '<div id="msg_1" class="success_msg_003"><div id="image" class="msg_003_image"></div>' + response.text + '</div>'
// output = '<div class="alert alert-success">×'+'<strong>'+response.title+'</strong>'+response.text +'</div>'
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
var credit = $.ajax({
url: "balance.php",
async: false
});
$("#credit").html(credit.responseText);
}
$("#result").hide().html(output).show();
}
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function () {
$('textarea[name=Recepient]').removeClass('inp-form-error');
$('<?php echo $type;?>[name=Sender]').removeClass('inp-form-error');
$('textarea[name=message]').removeClass('form-textarea-red');
$("#result").slideUp();
});
});
</script>
I am trying to show $("#wait").show(); until the server response returns. I am confused where to put "Wait" div. It should show waiting div until server response .
There was sleep of 5 second on server script to check if the wait div was working.
Show it in the beforeSubmit event option.
$('#form1').ajaxForm({
dataType: 'json',
beforeSubmit: function(){
$("#wait").show();
},
...
then hide it in the success function (which is called at the end of the loading).
success: function (response) {
$("#wait").hide();
...
Put this $("#wait").show() inside beforesubmit event of ajax request and $("#wait").hide() in ajax success event.

Categories

Resources