I have a page with roughly 20 enquiry buttons. Each button fires the same modal ajax PHP form. The form system works as it should, sending an email and triggering the success message. The success message displays inside the form tags but the rest of the form disappears leaving just tags.
The success message has a close button which closes the modal but the problem is that when I click any of the other enquiry buttons on the page they fire the modal but its still stuck on the success message.
Is there a way of using the modal close button as a sort of clear form trigger?
This is the ajax script im using…
<script>
function _(id){ return document.getElementById(id); }
function submitForm() {
_("sendenquiry").disabled = true;
_("status").innerHTML = 'please wait…';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "enquire.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("enquiry_form").innerHTML = '<p>Thanks '+_("n").value+', we will be in touch shortly.</p>';
} else {
_("status").innerHTML = ajax.responseText;
_("sendenquiry").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
This is my html
<!--enquiry modal-->
<div class="enquire-form-modal ef-effect" id="efmodal">
<div class="ef-content">
<div>
<form class="enquire-message" id="enquiry_form" onsubmit="submitForm(); return false;">
<fieldset>
<legend>Please fill out your enquiry below and we'll quickly get back to you.</legend>
<div class="">
<label class="" for="">Name</label>
<span><input type="text" id="n" class="" name="" placeholder="My name" required></span>
</div>
<div class="">
<label class="" for="">Email</label>
<span><input type="email" id="e" class="" name="email" placeholder="My email" required></span>
</div>
<div class="">
<label class="" for="">Enquiry</label>
<span><textarea id="m" class="" name="" placeholder="My enquiry" required></textarea></span>
</div>
<div>
<input id="sendenquiry" type="submit" value="SEND"> <span id="status"></span>
</div>
</fieldset>
</form>
<button class="ef-close">Close</button>
</div>
</div>
</div>
<div class="enquire-form-overlay"></div>
<!--enquiry modal end-->
Any help would be hugely appreciated. I’ve tried various things but nothing is working yet. If you need more code please let me know.
Thanks in advance
The problem is that you're replacing all of the form's html when the ajax call is complete. Try using the "status" div for housing the success message. Then, perhaps a simple setTimeout will suffice for clearing the message.
<script>
function _(id){ return document.getElementById(id); }
function submitForm() {
_("sendenquiry").disabled = true;
_("status").innerHTML = 'please wait…';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "enquire.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("status").innerHTML = '<p>Thanks '+_("n").value+', we will be in touch shortly.</p>';
} else {
_("status").innerHTML = ajax.responseText;
}
// clear the "status" message after 5 seconds
setTimeout(function() {
_("status").innerHTML = "";
}, 5000);
_("sendenquiry").disabled = false;
}
}
ajax.send( formdata );
}
</script>
Related
I have Simple code i had Created in Ajax,PHP and Mysql this code work fine in all Conditions Except one this one is wpdb Code to insert Data to table
<script type="text/javascript">
function _(id){ return document.getElementById(id); }
function submitForm(){
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "<?php bloginfo('template_directory'); ?>/ajax-insert.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "empty"){
_("status").innerHTML = '<div class="error"><p>Please Fill all of the Fields</p></div>';
}
if(ajax.responseText == "Done"){
_("status").innerHTML = '<div class="success"><p>Done</p></div>';
}
if(ajax.responseText == "error"){
_("status").innerHTML = '<div class="success"><p>Problem</p></div>';
}
}
}
ajax.send( formdata );
}
</script>
<form action="" onsubmit="submitForm(); return false;">
<div id="status"></div>
<label>Your Message</label><br>
<textarea cols="50" rows="10" type="text" name="m" id="m"></textarea>
<br>
<input name="submit" type="submit" value="Send">
</form>
ajax-insert.php
i had make code to insert data with some Conditions
this is the code
<?php
if(isset($_POST['m'])){
$message = $_POST['m'];
date_default_timezone_set("Africa/Cairo");
$date = date("Y/m/d h:i:sa");
}if(empty($message))
echo "empty";
elseif(!preg_match("~^[0-9a-z\-'\s\p{Arabic}]{1,60}$~iu", $message)){
echo "error";
}else{
echo "Done";
$insert = $wpdb->insert( 'chat_support', array( 'id' => '1', 'message' => $message , 'date' => $date, 'user' => $user_ID));
}
?>
if i try submit the form while textarea is Empty it give me Response that it is Empty but the Problem When i Write any thing to submit in database the code after Else dosen't work
The response be Please wait..... and This Response Still more thime without Doing and Thing
It is Highly advisable to use WordPress Ajax actions, you need to hookup your function to be called to wp_ajax and it would be available throughout the wp environment
Details about how to create and call ajax functions can be viewed from here https://codex.wordpress.org/AJAX_in_Plugins
I have a user settings page where the user changes their name via ajax and calls an update script that works great. The problem is I include a separate sidebar file which echos the current name in the database, but doesn't change until you reload the page because it's a separate sidebar.php include.
included sidebar.php within settings.php page
<h2 id="profile-name">
<?php
if(!$userRow['name']){
echo "You";
}else{
echo ucfirst($userRow['name']);
}
?>
</h2>
//form starts
<form id="my_form" onsubmit="submitForm(); return false;">
Name: <input id="name" type="text" class="form-control" placeholder= "<?php echo $userRow['name']; ?>" name="name" value="<?php echo $userRow['name']; ?>"><br>
<input class="btn btn-default" id="mybtn" type="submit" value="Submit Form"> <span id="status"></span>
</form>
//ajax works fine and updates database
function _(id){ return document.getElementById(id); }
function submitForm(){
var formdata = new FormData();
formdata.append( "name", _("name").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "update_name.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
} else {
// _("status").innerHTML = ajax.responseText;
alert("saved");
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
Just can't figure out how to get the sidebar to update without reloading the page. Thanks everyone!
I have a jQuery Ajax form that looks like this:
<form method="post" action="contact.php" class="contact-form">
<div class="contact-empty">
<input type="text" name="name" id="name" placeholder="Name *" class="txt-name" />
<input type="text" name="email" id="contact-email" placeholder="Email Address *" class="txt-email" />
<textarea rows="4" name="message" cols="60" id="message" placeholder="Message *" class="txt-message"></textarea>
<span class="btn-contact-container">
<button id="contact-submit" class="btn-contact">Submit</button>
<img src="images/loading.gif" alt="Loading..." width="62" height="62" id="contact-loading">
</span>
<span class="contact-error-field"></span>
</div>
<div class="contact-message"></div>
</form>
Here's my js that sends it:
$(document).ready(function () {
$('#contact-submit').click(function () {
$('.contact-error-field').hide();
var nameVal = $('input[name=name]').val();
var emailReg = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
var emailVal = $('#contact-email').val();
var messageVal = $('textarea[name=message]').val();
//validate
if (nameVal == '' || nameVal == 'Name *') {
$('.contact-error-field').html('Your name is required.').fadeIn();
return false;
}
if (emailVal == "" || emailVal == "Email Address *") {
$('.contact-error-field').html('Your email address is required.').fadeIn();
return false;
}
else if (!emailReg.test(emailVal)) {
$('.contact-error-field').html('Invalid email address.').fadeIn();
return false;
}
if (messageVal == '' || messageVal == 'Message *') {
$('.contact-error-field').html('Please provide a message.').fadeIn();
return false;
}
var data_string = $('.contact-form').serialize();
$('.btn-contact').hide();
$('#contact-loading').fadeIn();
$('.contact-error-field').fadeOut();
$.ajax({
type: "POST",
url: "contact.php",
data: data_string,
//success
success: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-check contact-success"></i>Your message has been sent.').fadeIn();
},
error: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-times contact-error"></i>Something went wrong, please try again later.').fadeIn();
}
}) //end ajax call
return false;
});
});
I have a subscribe form that uses the same code with just an email input and that submits fine on an iphone.
The contact form, however, gets stuck at 'Invalid email address.' when trying to submit from an iPhone even though the email you enter is correct. It works on desktop.
I've tried changing the button to a type="submit" input. Didn't change anything.
UPDATE: My regex was wrong, I replaced it with the following and it worked:
var emailReg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
Instead of using click() to submit your form, use submit():
Just change the top of your javascript code so it looks like this:
$(document).ready(function () {
$('form.contact-form').submit(function (e) {
e.preventDefault(); // <-- prevents normal submit behavior
And change your button to type=submit
<button type="submit" id="contact-submit" class="btn-contact">Submit</button>
I am building a sign up form, and want to include it into a div on the main page. The main page also includes a 'log in' form.
Both forms are included on the page using php include commands in the appropriate div i.e:
<?php include_once("login.php")?>
<?php include_once("signup.php")?>
Now when I use ajax on the second form i.e. the signup.php form, it sends back information from the fields in the first form. It doesn't help that they are both email and password fields.
Does anyone know how I can isolate the information from each form so i can send the data from each form separately? Below is all the relevant code for the forms and the Javascript.
Here is the code for the first form(login.php):
<form name="loginform" id="loginform" onsubmit="return false;">
<input style="margin-bottom:5px;" id="email" type="text" class="searchbox" onblur="checkusername()" maxlength="35" value="Email">
<span id="emailstatus"></span>
<input id="password" class="searchbox" type="password" onfocus="emptyElement('status')" maxlength="88" value="Password">
<p>Log In / <a href="#" onclick="forgotpass()">Forgot Password</p>
<span id="status"></span>
</form>
and the ajax for it:
function login(){
//isolate the variables from the form
var p = _("password").value;
var e = _("email").value;
var status = _("status");
if(e != "Email" && p != "Password"){
_("loginbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//start the Ajax Request
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
status.innerHTML = 'There was a problem. Please check your email and password and try again. ';
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?id="+ajax.responseText;
}
}
}
//data being sent by the ajax call
ajax.send("e="+e+"&p="+p);
} else {
status.innerHTML = "You're missing something..";
}
}
function emptyElement(x){
//The _(x) function is a shortcut for getElementById
_(x).innerHTML = "";
}
//This jQuery used to pre populate the email and password fields with "email" and "password"
$('input .seachbox').each(function(){
$(this)
.data('default', $(this).val())
.focus(function(){
if ($(this).val() == $(this).data('default')||''){
$(this).val() = ''
}
})
.blur(function(){
var default_val = $(this).data('default');
if($(this).val() == ''){
$(this).val($(this).data('default'))
}
});
});
and the second form(signup.php):
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Email Address:</div>
<input id="emails" type="text" class="searchbox" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" class="searchbox" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" class="searchbox" onfocus="emptyElement('status')" maxlength="16">
</form>
<br> Create Account<p>
<div class="statuserror"><span id="status" >This is a permanent error</span></div>
</div>
and the ajax for it:
function signup(){
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if( e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "OK"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
_("p1").innerHTML = "Please check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("e="+e+"&p="+p1);
}
EDIT - SOLUTION:- Have - after 3 days found a solution so stupid i had to share it. Basically I changed the id of the status div from "status" to "status1" and found that everything is working fine now. I think that it might be because on the login page I also have a div named status so the browser is unsure which div to put it in and just does nothing. This also explains why the signup.php page works when run alone in the browser but not when the login.php is included along with it in the main page.
Moral of the story - MAKE SURE YOUR IDS ARE ALL DIFFERENT!!
Thanks to everyone for the help.
jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.