I'm new to jQuery and have tried looking around for an answer on how to do this. I have 2 functions and I would like both to work together. The one function is submitHandler and its used to hide a form and at the same time add a class to a hidden element to unhide it - ie a thank you for submitting h1. The other function is to grab the input data and display it onsubmit in the form. So the problem is that I can get that one to work but then the other doesnt. Ie on form submit I can see the data input but not the h1 Thank you message.
Here are the functions:
SubmitHandler:
submitHandler: function() {
$("#content").empty();
$("#content").append(
"<p>If you want to be kept in the loop...</p>" +
"<p>Or you can contact...</p>"
);
$('h1.success_').removeClass('success_').addClass('success_form');
$('#contactform').hide();
},
onsubmit="return inputdata()"
function inputdata(){
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
return true;
},
The form uses PHP and jQuery - I dont know about AJAX but after some reading even less sure. Please help me out I dont know what I'm doing and at the moment I am learning but its a long road for me still.
Thank you
The form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform" onsubmit="return inputdata()">
<div class="_required"><p class="label_left">Name*</p><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><p class="label_left">E-mail address*</p><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<p class="label_left">Message</p><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<input type="submit" value="submit" name="submit" id="submit" />
</form>
The PHP bit:
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The Jquery Validate bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
Here is the full jQuery bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
});
});
Latest edit - Looks like this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
function submitHandler() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
function inputdata() {
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
},
$(document).ready(function(){
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
});
});
I know this question has already been answered and this isn't directly regarding the question itself; more so regarding the code in the question. However, I can't post comments as I'm a brand new member, but I just thought I'd highlight a few things in your code! Mainly consistency regarding the use of jQuery.
In the function supplied for 'submitHandler' - you empty $('#content') and then append HTML to it. This will work, but an easier method would be using the .html() function; note that this function can be used to return the HTML contained inside an element; but that's when no arguments are supplied. When you supply an argument, it re-writes the content of the html element. Additionally, I would most likely use the .show() method on the h1 success element; if only for code readability.
For example:
submitHandler: function(){
$('#content').html( "<p>If you want to be kept in the loop...</p>"
+ "<p>Or you can contact...</p>");
$('h1.success_').show();
$('contactform').hide();
}
As for inputdata() - you seem to have strayed off of the jQuery ethos here a little again, I'd aim for consistency when using jQuery personally - but also as the jQuery syntax makes the traditional javascript 'document.getElemen...' object look a bit outdated/it's extra to type. At its most basic jQuery is essentially best viewed as a wrapper for the document object - just with added syntactical sugar. Additionally, it allows you to chain methods - so the last two expressions can essentially be "dressed up" to look as one when using jQuery.
I'd personally use .val(), .html() and .css() functions; example:
function inputdata(){
var usr = $('#contactname').val();
var eml = $('#email').val();
var msg = $('#message').val();
$('#out').html( usr + " " + eml + msg )
.css('display', 'block');
return true;
}
Your submitHandler function isn't called. That's why it doesn't work.
Add this to your code:
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
EDIT:
try this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
CHange return true, to return false in the inputdata function
Related
I have a page with two forms. I need to know which button is submitting the form. When the form gets submitted I am checking the set status of the button, but it doesn't seem to be set. Can anyone help?
HTML
<div id="contact-wrapper" class="">
<h1 style="color: white">Send me an email.</h1>
<div id="msg-status"></div>
<form id="contact" method="post">
<div class="contact-title">Email Address</div>
<input type="email" name="emailAddress" id="email-addr-txt" placeholder="Your Email Address" require>
<div class="contact-title">Subject</div>
<input type="text" name="emailSubject" id="email-subject-txt" placeholder="Subject" require>
<div class="contact-title">Message</div>
<textarea name="emailMessage" id="email-msg-txt" placeholder="Message" require></textarea>
<input type="submit" name="sendBtn" value="Send" id="send-msg-btn">
</form>
</div>
PHP
<?php
$phpconsole = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
if (isset($_POST["loginBtn"])) {
//Do Stuff
}
if (isset($_POST["sendBtn"])) {
//Do Stuff
}
$phpconsole = var_dump($_POST); }
?>
JavaScript
$('#contact').submit(function(e){
e.preventDefault();
email_regex = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
var msg = "";
if ($('#email-addr-txt').val() == ""){
msg += "<p>The email address is missing!</p>";
} else if (!email_regex.test($('#email-addr-txt').val())) {
msg += "<p>The email address is invalid!</P>"
}
if ($('#email-subject-txt').val() == "") {
msg += "<p>The Subject is missing!</p>";
}
if ($('#email-msg-txt').val() == "") {
msg += "<p>The message is missing!</p>"
}
var heightOfContactWrapper = $('#contact-wrapper').height();
if (msg != "") { // There were errors that need to be delt with before sending message.
msg = "<h2>There were errors.</h2>" + msg;
$('#msg-status').html(msg);
$('#msg-status').addClass('msg-status-fail');
var heightOfMsgStatus = $('#msg-status').height() + $('#contact-wrapper').height() + "px";
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
} else { //No errors found.
$('#msg-status').removeClass('msg-status-fail');
$('#msg-status').addClass('msg-status-success');
$('#msg-status').html("<h2>Message is sending. Please wait.</h2>")
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
$('#contact').unbind('submit').submit();
}
});
Output of var_dump is
array(3) { ["emailAddress"]=> string(13) "asdf#aedf.com"
["emailSubject"]=> string(4) "asdf" ["emailMessage"]=> string(4)
"asdf" }
Errors are:
Notice: Undefined index: loginBtn in /var/www/new-site/index.php on
line 5 Notice: Undefined index: SendBtn in /var/www/new-site/index.php
on line 5
The problem is that your Javascript code ends up being the thing that triggers the form submit, not your button. If you removed your JS code you'd see your sendBtn value.
Instead of calling e.preventDefault in your .submit() callback, you could just return true if you want the form submission to continue, or false if you don't. That way, you don't have to call $('#contact').submit() to get your form to submit, or even unbind your submit handler. Something like this:
$('#contact').submit(function(e){
email_regex = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
var msg = "";
if ($('#email-addr-txt').val() == ""){
msg += "<p>The email address is missing!</p>";
} else if (!email_regex.test($('#email-addr-txt').val())) {
msg += "<p>The email address is invalid!</P>"
}
if ($('#email-subject-txt').val() == "") {
msg += "<p>The Subject is missing!</p>";
}
if ($('#email-msg-txt').val() == "") {
msg += "<p>The message is missing!</p>"
}
var heightOfContactWrapper = $('#contact-wrapper').height();
if (msg != "") { // There were errors that need to be delt with before sending message.
msg = "<h2>There were errors.</h2>" + msg;
$('#msg-status').html(msg);
$('#msg-status').addClass('msg-status-fail');
var heightOfMsgStatus = $('#msg-status').height() + $('#contact-wrapper').height() + "px";
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
return false;
} else { //No errors found.
$('#msg-status').removeClass('msg-status-fail');
$('#msg-status').addClass('msg-status-success');
$('#msg-status').html("<h2>Message is sending. Please wait.</h2>")
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
return true;
}
});
I am trying to send an email with PHP and AJAX, and it finally works, but it won't display validation errors returned from the server. I guess I'm doing something wrong in iterating through that data, or just don't understand something with connecting PHP and jQuery with JSON.
PHP mail script on server:
$to = "mymail#gmail.com";
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
if (empty($_POST['name'])) {
$errors[] = "Molimo unesite Vaše ime";
} else {
$contact_name = htmlentities($_POST['name']);
}
if (empty($_POST['mail'])) {
$errors[] = "Molimo unesite Vašu email adresu.";
} else if (strlen($_POST['mail']) > 60) {
$errors[] = "Vaša email adresa je predugačka.";
} else if (filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL) === false ) {
$errors[] = "Unesite validnu email adresu.";
} else {
$contact_mail = "<" . htmlentities($_POST['mail']) . ">";
}
if (empty($_POST['text'])) {
$errors[] = "Molimo unesite poruku.";
} else {
$contact_text = htmlentities($_POST['text']);
}
}
if (empty($errors) === true) {
if(isset($contact_text, $contact_name, $contact_mail)) {
$subject = "Mail from " . $contact_name ." via www.mysite.com";
$headers = "From: " . $contact_mail;
$sent = mail($to, $subject, $contact_text, $headers);
if ($sent) {
die("true");
} else {
return json_encode($errors);
}
}
}
Relevant jQuery:
var mailBroker = {
send : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
if (contact_name === "" || contact_mail === "" || contact_text === "") {
//form not complete
} else {
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
} else {
var parsedData = $.parseJSON(data);
$.each(parsedData, function() {
var that = $(this);
setStatus(that);
});
}
});
}
},
setStatus : function(status) {
$('textarea[name="contact-text"]').after('<span>' + status + '</span>');
}
}
And inside $(document).ready():
$('#contact-us form').submit(function(event) {
event.preventDefault();
mailBroker.send();
$(this).trigger('reset');
});
Can somebody point out what I am doing wrong?
Of course, I know that I could just do it on the client-side, but that it is bad practice. So I left that part out for now and assumed that invalid or no data got through for required form fields.
Answer form is easier to explain this. The logic in your code never gives your script a chance to output the errors to the AJAX. You'd need to change the logic so it will. Ie.
if (empty($errors) === true) {
if(isset($contact_text, $contact_name, $contact_mail)) {
$subject = "Mail from " . $contact_name ." via www.mysite.com";
$headers = "From: " . $contact_mail;
$sent = mail($to, $subject, $contact_text, $headers);
if ($sent) {
die("true");
} else {
die("false"); // with json_encode here, $errors will always be empty
}
}
} else {
die(json_encode($errors)); //$errors wasn't empty, this is where you need to hand it back to the JS.
}
This is why firebug or another tool would help. You'd see that the information you were wanting given to your JS wasn't there - that way you know to look at the PHP (server-side) since it isn't outputting as expected. If it was, you'd check in to the JS code to see why that isn't processing it as expected.
EDIT: Your javascript doesn't allow the PHP to execute when a field is empty, but you are wanting the feedback PHP will give if one is empty, so you'd want to change your JS to something like:
var mailBroker = {
send : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
} else {
var parsedData = $.parseJSON(data);
$.each(parsedData, function() {
var that = $(this);
setStatus(that);
});
}
});
},
setStatus : function(status) {
$('textarea[name="contact-text"]').after('<span>' + status + '</span>');
}
}
A little modification of Jon's answer because you will still need to extract the messages from the returned JSON:
var mailBroker = {
'send' : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
$('#contact-us form').trigger('reset');
} else { //validation failed
var parsedData = $.parseJSON(data);
var msg = '';
$.each(parsedData, function() {
var that = $(this);
for (var i = 0; i < that.size(); i++) {
msg += that[i];
}
mailBroker.setStatus(msg); //msg used to be 'that'
msg = '';
});
}
});
},
'setStatus' : function(status) {
$('#validation-msgs').prepend('<p class="validation-msg">' + status + '</p>');
}
}
Essentially - you will need to pass through parsed data to get each of the messages. The problem is that they are also stored as arrays - of characters. So you will need to pass through those, too, and append those characters to a message String.
Then, you should prepend those messages to some container for warnings so they are in the right order. If you don't do that, you will get [Object] instead of the message text.
Hope this helps.
Hi I think you messed up on your line 3 mail script.
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
because you will use comparison operators for that.
Like this below.
if (isset($_POST['name'] && $_POST['mail'] && $_POST['text'])) {
I cannot seem to find the problem in my code. I want the validation in php file to trigger the jquery notification plugin 'toastr', however, the php echo keeps publishing the php file message status to a new tab, instead. What am I doing wrong and how can I make the message appear in the notification, instead? The live version of my school site is here: Wright State University BMES Site and the problem can be replicated when submitting the Contact Us form. Thank you in advance :)
HTML:
<form action=send-contact.php method=post data-show-errors="true" class=contact-form id=contact-form-id data-parsley-validate>
<p class=half>
<input autofocus parsley-trigger="change" name=name required id=name placeholder="Type your name" class="testBox label_better" data-new-placeholder="Example: Sir Humphrey Charleston III" parsley-required="true">
</p>
<p class=half>
<input name=email id=email placeholder="Type your e-mail address" class="testBox label_better" data-new-placeholder="Example: humphrey.charleston#wright.edu" parsley-type="email" parsley-trigger="change" required parsley-required="true">
</p>
<p>
<select class="contactselect required" name=subject id=subject parsely-required="true" required parsley-trigger="change">
<option value="" parsley-trigger="change">Please select one topic:</option>
<option value="1" parsley-trigger="change">Information about BMES Chapter</option>
<option value="2" parsley-trigger="change">Information about upcoming events</option>
<option value="3" parsley-trigger="change">Other</option>
</select>
</p>
<p>
<textarea name=message id=message rows=12 cols=20 class="label_better_text" placeholder="Tell us what's on your mind." parsley-trigger="keyup" parsley-rangelength="[1,300]" required parsley-required="true"></textarea>
</p>
<p>
<button name=send type=submit onclick="$( '#contact-form-id' ).parsley('validate')" id=submit value=1>Send message</button>
<span class="color-red"><button onclick="$( '#contact-form-id' ).parsley( 'destroy' ); $('#contact-form-id').parsley();" name=reset type=reset value=1>Reset</button></span>
</p>
</form>
<script type=text/javascript>
jQuery(document).ready(function(c){
$('#contact-form').parsley();
$('#contact-form-id').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
$.post("send-contact.php", $(this).serialize());
toastr.success('Thank you, we will attend to your message shortly.');
$( '#contact-form-id' ).parsley( 'destroy' );
}
}); });
</script>
PHP:
<?php
$name = '';
$subject = '';
$email = '';
$message = '';
function getIp()
{if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip_address=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (!isset($ip_address)){
if (isset($_SERVER['REMOTE_ADDR']))
$ip_address=$_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
//taking the data from form
$name = addslashes(trim($_POST['name']));
$subject = addslashes(trim($_POST['subject']));
$email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
//form validation
$errors = array();
$fields = array();
if(!$name) {
$errors[] = "Please enter your name.";
$fields[] = "name";
}
$email_pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\#([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(!$email) {
$errors[] = "Please enter your e-mail address.";
$fields[] = "email";
} else if(!preg_match($email_pattern, $email)) {
$errors[] = "The e-mail address you provided is invalid.";
$fields[] = "email";
}
if(!$subject) {
$errors[] = "Please choose the subject of your message.";
$fields[] = "subject";
}
if(!$message) {
$errors[] = "Please enter your message.";
$fields[] = "message";
}
//preparing mail
if(!$errors) {
//taking info about date, IP and user agent
$timestamp = date("Y-m-d H:i:s");
$ip = getIp();
$host = gethostbyaddr($ip);
$user_agent = $_SERVER["HTTP_USER_AGENT"];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
$headers .= "From: $email\n";
$content = 'Subject: '.$subject.'<br>'.
'Name: '.$name.'<br>'.
'E-mail: '.$email.'<br>'.
'Message: '.$message.'<br>'.
'Time: '.$timestamp.'<br>'.
'IP: '.$host.'<br>'.
'User agent: '.$user_agent;
//sending mail
$ok = mail("my-email-address-normally-goes-here","BMES Website Contact Us ", $content, $headers);
if($ok) {
$response['msgStatus'] = "ok";
$response['message'] = "Thank you for contacting us. We will attend to your inquiry as soon as possible.";
} else {
$response['msgStatus'] = "error";
$response['message'] = "An error occured while trying to send your message. Please try again.";
}
} else {
$response['msgStatus'] = "error";
$response['errors'] = $errors;
$response['errorFields'] = $fields;
}
header('Content-type: application/json');
echo json_encode($response);
?>
Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var formTop = form.offset().top;
var url = form.attr("action");
var data = form.serialize();
form.find("input, select, textarea, span").removeClass("error");
form.find(".msg").remove();
button.html("Sending...");
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
form.prepend('<p class="msg success"><a class="hide" href="#">hide this</a>' + msg + '</p>');
form.find("input, select, textarea").val("");
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
form.prepend('<div class="msg error"><a class="hide" href="#">hide this</a><p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p></div>');
} else form.prepend('<p class="msg error"><a class="hide" href="#">hide this</a>' + msg + '</p>');
}
$(".msg a.hide").click(function(e){
e.preventDefault();
$(this).parent().slideUp();
});
button.html(buttonText);
window.scrollTo(0, formTop);
}, 'json');
})
});
Have you tried playing with your jquery a bit more? for instance, ajax instead of post.
something like this?
button.click(function () {
$.ajax({
url: url,
type: 'POST',
data: form.serialize(),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.msgSTatus == "ok"){
alert(data.message);
// play with html here once you know the page stays.
}
},
error: function (data) {
alert('Fail.');
}
});
});
As far as html appending goes, I would personally have an empty on the page already with an id, and just set the content of the div to the data that you receive, would make the js look much cleaner maybe..
Try including jquery before your other scripts. Also, use Firebug or build-in browser JS debugging tools to troubleshoot Javascript errors.
I have managed to solve the issue. Alterations are listed below for comparative purposes to not only help others but to also close this issue. A special thank you to #WhiteRuski for pointing me in the right direction. The PHP and HTML remain unchanged. Here is the new Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var url = form.attr("action");
var data = form.serialize();
// button.html("Sending...");
button.html('<i class="fa fa-cog fa-lg fa-spin"></i>' + ' Sending ... ');
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
toastr.success('<p>' + msg + '</p>');
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
// toastr.error('<p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p>'); This lists the specific errpr in the field
toastr.error('<p>There were a few errors in your form. Please resubmit with corrections.</p>');
} else toastr.error('<p>' + msg + '</p>');
}
button.html(buttonText);
}, 'json');
})
});
I am writing code to make a basic chatroom. The code I have takes lines entered into the input textbox, then uses Ajax to write to a random filename, then I have javascript loop every second using setInterval to load and display from the text file.
After the user logs in with information that populates a MySQL database I want to have a basic welcoming message automatically saved to the text file upon entering the chat. I do this by calling my saveData function with username as 'Host' and then the welcoming message which is declared in a variable.
The function that sends the login information to the database and the function that saves the welcoming message are both called under the login() function. The login() function is called after submitting the info form.
Here is the problem: I cannot get the functions, saveLogin() and saveData(), to BOTH fully execute when called under login(). If I comment one out and NOT the other, the function will work fine. So they work independently, but not together. If both functions are called then saveData() works fine, but saveLogin() will not. I have no idea why.
I was able to narrow the problem down to the 'XMLHttpRequestObject.send' event under the saveLogin() function. The rest of that function appears to be executed. I thought maybe it was a problem with the variable names or something, so I tried some variations, but nothing has resolved the issue.
<script language = "javascript">
// loads XML HTTP per browser type
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
//create random string
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
rString = randomString(128);
filename = rString;
// loads chat lines from file using POST method with timer
function getData(geturl)
{
if(XMLHttpRequestObject) {
geturl = "getdata.php";
XMLHttpRequestObject.open("POST", geturl);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
document.formChat2.textarea1.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("filename=" + filename);
}
}
// saves new chat line to file
function saveData(filename, username, newline)
{
if(XMLHttpRequestObject && document.formChat1.txtLine.value != "" || username == "Host") {
var url = "savedata.php";
XMLHttpRequestObject.open("POST", url);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
}
}
XMLHttpRequestObject.send("filename=" + filename + "&username=" + username + "&newline=" + newline);
document.formChat1.btnDisplay.click();
document.formChat1.txtLine.value = "";
}
}
// saves login info to database
function saveLogin(filename, username, email, phone, weburl)
{
if(XMLHttpRequestObject) {
var loginurl = "login.php";
XMLHttpRequestObject.open("POST", loginurl);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
}
}
XMLHttpRequestObject.send("filename=" + filename + "&username=" + username + "&email=" + email + "&phone=" + phone + "&weburl=" + weburl);
}
}
function login(divID) {
username = document.formLogin.txtLogin.value;
email = document.formLogin.txtEmail.value;
phone = document.formLogin.txtPhone.value;
weburl = document.formLogin.txtURL.value;
saveLogin(filename, username, email, phone, weburl);
var obj = document.getElementById(divID);
obj.innerHTML = "<div id='targetDiv'><form name='formChat1' method='POST' onSubmit='return false;'><input type='text' name='txtLine' id='txtLine' size='30'><input type='button' name='btnDisplay' value='Display Message' onclick=\"setInterval('getData(filename)', 1000);\"><input type='button' name='btnSave' value='Send Message' onclick='saveData(filename, username, txtLine.value)'></form><form name='formChat2'><textarea name='textarea1' id='textarea1' rows='10' cols='50'></textarea></form></div>";
welcome = "Welcome to the chat.";
saveData(filename, 'Host', welcome);
}
</script>
<div id="targetDiv">
<form name="formLogin" method="POST">
Please enter your info:<br>
<input type="text" name="txtLogin" id="txtLogin" size="50" value="Name (Required)" onfocus="document.formLogin.txtLogin.value=''"><br>
<input type="text" name="txtEmail" id="txtEmail" size="50" value="Email Address (Required)" onfocus="document.formLogin.txtEmail.value=''"><br>
<input type="text" name="txtPhone" id="txtPhone" size="50" value="Phone Number (Optional)" onfocus="document.formLogin.txtPhone.value=''"><br>
<input type="text" name="txtURL" id="txtURL" size="50" value="Website URL (Optional)" onfocus="document.formLogin.txtURL.value=''"><br>
<input type="button" name="btnLogin" value="Login"
onclick="login('targetDiv');">
</form>
</div>
You need to use different XHR objects, so that you can get both responses, since you're sending both AJAX requests at the same time.
Write a function like:
function getXHR() {
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
return XMLHttpRequestObject;
}
Then call it in each of the functions that performs AJAX requests, with:
var XHRObject = getXHR();
and use that within the function.
I tried looking at past posts but didn't see anything that would help my situation. I created an ajax post with validation for my website but for some reason it won't work with the validation. If I drop the code seperately from validation the POST works (without validating).
Chrome is returning a "Uncaught ReferenceError: getdetails is not defined: onclick" error, however I'm lost as to why? Because all the fields have valid data in them when I try the form. Here's my code below:
html code
<input type="submit" name="submit" id="submit_btn" class="button" value="Send" onClick = "getdetails()" />
rsvp-form.js
jQuery.noConflict();
jQuery( document ).ready( function( $ ) {
jQuery.timer = function(time,func,callback){
var a = {timer:setTimeout(func,time),callback:null}
if(typeof(callback) == 'function'){a.callback = callback;}
return a;
};
jQuery.clearTimer = function(a){
clearTimeout(a.timer);
if(typeof(a.callback) == 'function'){a.callback();};
return this;
};
/* RSVP Form */
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#ffefae"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var attending = $("input#attending").val();
if (attending == "") {
$("label#attending_error").show();
$("input#attending").focus();
return false;
}
//var dataString = 'name='+ name + '&email=' + email + '&attending=' + attending;
//alert (dataString);return false;
function getdetails() {
var name = $('#name').val();
var email = $('#email').val();
var attending = $('#attending').val();
$.ajax({
type: "POST",
url: "/wp-content/themes/Retro/sqlpost/details.php",
data: {name:name, email:email, attending:attending}
}).done(function( result ) {
$('#contact_form').html("<br /><div id='message' style='display:table-cell; vertical-align:middle; text-align:center;'></div>");
$('#message').html("Thanks for RSVP'ing " +name +",<br />we can't wait to see you!")
//.hide()
fadeIn(1500, function() {
$('#message');
});
})
}
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
details.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$attending = $_POST['attending'];
mysql_connect("mkschool.db.10611925.hostedresource.com","mkschool","Correct1!");
mysql_select_db("mkschool");
$query="INSERT into students (name, email, attending) VALUES ('".$name."','".$email."','".$attending."')";
mysql_query($query) or die ('Error updating database');
//echo "Thanks for RSVP'ing " .$name. ", we can't wait to see you!"; //
?>
Remove onClick = "getdetails()" event from your submit button:
<input type="submit" name="submit" id="submit_btn" class="button" value="Send" />
And Modify $(".button").click(); Jquery handler as follows:
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var attending = $("input#attending").val();
if (attending == "") {
$("label#attending_error").show();
$("input#attending").focus();
return false;
}
//var dataString = 'name='+ name + '&email=' + email + '&attending=' + attending;
//alert (dataString);return false;
var name = $('#name').val();
var email = $('#email').val();
var attending = $('#attending').val();
$.ajax({
type: "POST",
url: "/wp-content/themes/Retro/sqlpost/details.php",
data: {name:name, email:email, attending:attending},
success:
function( result ) {
$('#contact_form').html("<br /><div id='message' style='display:table-cell; vertical-align:middle; text-align:center;'></div>");
$('#message').html("Thanks for RSVP'ing " +name +",<br />we can't wait to see you!")
//.hide()
fadeIn(1500, function() {
$('#message');
});
return false;
}
});
});
Change the type of the input type="submit" to type="button" the HTML
<input type="button" name="submit" id="submit_btn" class="button" value="Send" onClick = "getdetails()" />
You can also use preventDefault() function of Jquery Libraray.