How to submit a form using AJAX? - javascript

I am trying to submit a form using ajax. However, it is not showing the message that the code is wrong. I push errors the same way on the entire website so that part works.
This is my code:
<script type="text/javascript" src="jquery.js"></script>
<div id="showerrors"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#showerrors').load('errors2.php')
}, 1000);
});
</script>
<form id="formoid" method="post" action="data/newpass.php">
<div class="row2">
<input type="email" class="form-control2" placeholder="email adres" aria-describedby="basic-addon1" name="email" required>
</div>
<div class="row2">
<input type="text" class="form-control2 pull-left" placeholder="Enter code" aria-describedby="basic-addon1" name="captcha" style="width: 70%;" required>
<div class="capbg1">
<input type="text" class="disable1b pull-right" value="<?php echo $capcode3;?>" name="captcha" style="width: 29%;" disabled>
</div>
</div>
<div class="row2"></div>
<div class="row2">
<button type="submit" class="w3-black pull-left" name="req_new_pw">Request new password</button>
</div>
</form>
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : { email: $('#email').val(), captcha: $('#captcha').val() },
});
});
</script>
// newpass.php - action in the form
<?php
error_reporting(E_ALL);
session_start();
ob_start();
$db = mysqli_connect(***);
if (isset($_POST['req_new_pw']))
{
$captcha = mysqli_real_escape_string($db, $_POST['captcha']);
$email = mysqli_real_escape_string($db, $_POST['email']);
if(isset($_SESSION['capcode3']))
{
if($_SESSION['capcode3'] != $captcha)
{
array_push($errors, "- Code is incorrect.");
}
}
}
?>
//errors.php
<?php if (count($errors) > 0) : ?>
<div class="isa_error">
<i class="fa fa-times-circle"></i>
<b>Oops..</b><br>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
//errors2.php - display errors above form
<?php
include('errors.php');
if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</div>
</h3>
</div>
<?php endif ?>
When i submit the form, nothing happens.
What am i doing wrong?

You don't send $_POST['req_new_pw'] and you are asking if it's set.
You can use serialize() to send all form element by post:
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
Make sure you are setting $_SESSION['capcode3'] either.

This works like a charm:
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});

Related

how to submit form how to get session count without reloading page on form submission

I create a form with hidden input forms that submit the value to a PHP script and store each value in an array of sessions by reloading the page with AJAX. It returns an HTML success alert message to <p id ="msg"></p>. I need help on how to send $count to <p id="count"></p> and success alert message to <p id ="msg"></p> at the point of success: in AJAX. And also I will like the success alert to disappear after 3 seconds of the display. Below is my code:
my_add_cart.php
<?php
session_start();
$_SESSION['title'][]=$_POST['title'];
$_SESSION['price'][]=$_POST['price'];
$_SESSION['img_src'][]=$_POST['img_src'];
$count = count($_SESSION["title"]);
echo $count;
echo '<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display=\'none\';">×</span>
<center>Product added successfully to cart.</center>
</div>';
exit();
?>
Above is my_add_cart.php and below is my HTML and javascript:
<script type="text/javascript">
function clickButton(){
var title=document.getElementById('title').value;
var price=document.getElementById('price').value;
var img_src=document.getElementById('img_src').value;
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src
},
cache:false,
success: function (html)
{
$('#msg').html(html);
}
});
return false;
}
</script>
<html>
<p id="msg"></p>
<p id="count"></p>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "price" id="price" >
<input type="hidden" value="<? echo "https://mikeandcathy.com.ng/admin/UploadFolder/".$row_product_img[0]; ?>" name = "img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
</html>
I Suggest turning your server code into a json api
Solution
change my_add_cart.php to this
<?php
session_start();
$_SESSION['title'][]=$_POST['title'];
$_SESSION['price'][]=$_POST['price'];
$_SESSION['img_src'][]=$_POST['img_src'];
$count = count($_SESSION["title"]);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(
[
'count' => $count,
'message' => '<div class="alert"><span class="closebtn" onclick="this.parentElement.style.display=\'none\';">×</span> <center>Product added successfully to cart.</center></div>';
]
);
exit();
?>
change your frontend code to this
<script type="text/javascript">
function clickButton(){
var title=document.getElementById('title').value;
var price=document.getElementById('price').value;
var img_src=document.getElementById('img_src').value;
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src
},
cache:false,
success: function (data)
{
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
<html>
<p id="msg"></p>
<p id="count"></p>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "price" id="price" >
<input type="hidden" value="<? echo "https://mikeandcathy.com.ng/admin/UploadFolder/".$row_product_img[0]; ?>" name = "img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
</html>

insert data in database dynamically

$query = "select * from comments t1 inner join users t2 on t1.user_id = t2.UserId where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <?php echo $username; ?></span></label><br>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
$(document).ready(function(){
$(".reply").click(function(){
var current = $(this).attr("data-role");
$('.replyForm[data-role="'+$(this).attr("data-role")+'"]').fadeIn();
});
});
</script>
<?php
if(isset($_POST['reply']))
{
echo "<script>alert('$commentid')</script>";
}
?>
<?php } ?>
it is a simple comment system with each comment there is a reply link on click on reply link a textbox is shown . I want to enter comment reply to database table therefore I want to get the record of the specific comment. How to do that with PHP.
this code should do what you want, completely dinamically
<div class="jumbotron comment-container" data-pk="<?php echo $commentid; ?>">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<em class="text-muted"><?php echo $ageDate; ?></em>
</div>
<div class="col-md-12">
<label>Comment by <?php echo $username; ?></label><br/>
<button class="btn btn-primary reply">Reply</button>
</div>
</div>
</div>
And here is the JS part. In order to reduce the code printed in the while loop, the reply form is cloned each time and appended where needed.
var reply_form = $('<div class="row replyForm-container"><div class="col-md-12">'+
'<form method="post" class="reply-form">'+
'<textarea class="form-control" rows="4">Prefilled content</textarea><br>'+
'<br>'+
'<button type="submit" name="reply" class="btn btn-primary" style="float:right" >Reply</button>'+
'</form>'+
'</div></div>');
$(".reply").click(function(){
$(this).hide();
var $container = $(this).closest('.comment-container');
var pk = $container.data('pk');
var rf_clone = reply_form.clone();
rf_clone.find('form').attr('data-pk', pk).data('pk', pk);
$container.append( rf_clone.hide().fadeIn(1000) );
});
// working with dynamical elements, we need to use delegation here
$(document).on('submit', '.reply-form', function(e){
e.preventDefault();
var reply_container = $(this).closest('.replyForm-container');
var pk = $(this).data('pk');
var reply = $(this).find('textarea').val();
console.log('Insert reply "'+reply+'" for comment ID: '+pk);
$.ajax({
type: "POST",
url: 'my_php_handler.php',
async: false,
dataType: "json",
data: {action: 'add-reply', commend_id: pk, reply_text: reply},
success: function (response) {
if( response ) {
reply_container.fadeOut('slow', function(){
var btn = reply_container.closest('.comment-container').find('button.reply');
$(this).remove(); //will remove the element after fadeOut completes
btn.show();
})
}
}
});
});
Check working Fiddle (ajax disabled)

AJAX comment system Validation problems

So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique

add and retrieve record from mysql using ajax

As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors

How do I reset an email form after submission so that another email can be sent without refreshing the page

I have this form I've been playing around with in Wordpress.
It works, but here is the problem...
When the page loads, the contact form is blank (obviously)
If info is not put in text fields, form will not send (obviously)
If info IS put in text fields it will send, "Submit" button will disable and the text on the "Submit" button will change from "Submit Message" to "Submitting, please wait..."
When message has finished sending, a "success message" will pop up over the form for 2.5 seconds, the input fields will be cleared back to a blank form, "Submit" button text reverts back to original "Submit Message" text.
Now, WITHOUT refreshing the page, I want to send a NEW message using the blank form.
I fill in all fields, hit send, and I get an error message saying "Invalid email. You must enter at least one email address." - (the source of this message, I have no idea... I didn't make it, and I have searched high and low through Wordpress files and cannot find where it is coming from)
This error message is referring to the "mail to" email address, which the code pulls from the Wordpress Admin settings.
For some reason, after the form is submitted the first time, it "uses" that mail-to address, and will not allow it to be used again unless the page is reset.
Is there a solution here so that I can send a message... form will automatically clear... I can send a new message, form will automatically clear... I can send a new message... and so on, WITHOUT having to refresh the page after each message submission.
Here is the code:
<?php /* Template Name: Contact Form */ ?>
<?php get_header(); ?>
<div id="top-div"></div>
<div id="container">
<div id="inner-headline">
<h2>
<?php
$headline = get_post_meta($post->ID, "_headline", $single = false);
if(!empty($headline[0]) )
{
echo $headline[0];
}
else
{
the_title();
}
?>
</h2>
</div>
<div id="content">
<div id="content-inner">
<div class="sideright-left-col">
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)): ?>
<p class="error"><?php _e('There was an error submitting the form.',
'Sona')?><p>
<?php endif ?>
<div id="status"></div>
<form action=() id="contact-form" method="post">
<div class="name">
<label for="contactName"><span style="color: red;">*&nbsp</span>
<?php _e( 'Name', 'Sona' ); ?>:
</label>
<input type="text" name="contactName" id="contactName"
value="<?php if(isset($_POST['contactName'])) echo
$_POST['contactName'];?>" class="requiredField txt"/>
<?php if(isset($nameError) && $nameError != ''): ?><span
class="error"><?php echo $nameError;?></span><?php endif;?>
<div class="clear"></div>
</div>
<div class="email">
<label for="email"><span style="color: red;">*&nbsp</span>
<?php _e( 'E-mail', 'Sona' ); ?>:
</label>
<input type="text" name="email" id="email"
value="<?php if(isset($_POST['email'])) echo
$_POST['email'];?>" class="requiredField email txt" />
<?php if(isset($emailError) && $emailError != ''): ?><span
class="error"><?php echo $emailError;?></span><?php endif;?>
<div class="clear"></div>
</div>
<div class="subject">
<label for="subject"><span style="color: red;">*&nbsp</span>
<?php _e( 'Subject', 'Sona' ); ?>:</label>
<input type="text" name="subject" id="subject"
value="<?php if(isset($_POST['subject'])) echo
$_POST['subject'];?>" class="requiredField txt"/>
<?php if(isset($subjectError) && $subjectError != ''): ?><span
class="error"><?php echo $subjectError;?></span><?php endif;?>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="message">
<label for="message"><span style="color: red;">*&nbsp</span>
<?php _e( 'Message', 'Sona' ); ?>:</label>
<textarea name="message" cols="100" rows="200" id="message"
class="txt requiredField"><?php echo isset($_POST['message']) &&
$_POST['message']!='' ? stripslashes($_POST['message']) : ''?>
</textarea>
<?php if(isset($messageError) && $messageError != '') { ?><span
class="error"><?php echo $messageError;?></span> <?php } ?>
<div class="clear"></div>
</div>
<div>
<?php
$al_options = get_option('al_general_settings');
$options = array(
$al_options['al_contact_error_message'],
$al_options['al_contact_success_message'],
$al_options['al_subject'],
$al_options['al_email_address'],
);
?>
<input type="hidden" name = "options" value="
<?php echo implode(',', $options) ?>" />
<br />
<input type="submit" class="button white-back"
value="Submit Message" tabindex="5" id="submit" name="send"/>
<div class="clear"></div>
</div>
</form>
</div>
<div class="sideright-right-col">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Contact
Sidebar") ) : ?> <?php endif;?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<?php endwhile; ?>
<?php endif; ?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#contact-form").validate({
submitHandler: function() {
var postvalues = jQuery("#contact-form").serialize();
jQuery('#submit').attr('disabled',"disabled");
jQuery('#submit').attr('value', "Submitting, please wait...");
jQuery.ajax
({
type: "POST",
url: "<?php echo get_template_directory_uri() ?>/contact-form.php",
data: postvalues,
success: function(response)
{
jQuery('#status').addClass('success-
message').html(response).show().delay(2500).fadeOut();
jQuery('input:not(#submit)').val("");
jQuery('textarea').val("");
jQuery('#submit').attr('value', "Submit Message");
jQuery('#submit').removeAttr('disabled');
}
});
return false;
},
focusInvalid: true,
focusCleanup: false,
rules:
{
contactName: {required: true},
email: {required: true, minlength: 6,maxlength: 50, email:true},
message: {required: true},
subject: {required: true}
},
messages:
{
contactName: {required: "<?php _e( 'This field is required', 'Sona' ); ?>"},
email: {required: "<?php _e( 'This field is required', 'Sona' ); ?>",
email: "<?php _e( 'Please provide a valid e-mail address.', 'Sona' ); ?>"},
message: {required: "<?php _e( 'This field is required', 'Sona' ); ?>"},
subject: {required: "<?php _e( 'This field is required', 'Sona' ); ?>"}
},
errorPlacement: function(error, element)
{
error.insertAfter(element);
},
invalidHandler: function()
{
jQuery("body").animate({ scrollTop: 0 }, "slow");
}
});
});
</script>
<?php get_footer(); ?>
Try this,
Inside your ajax response section after submitting the form you got success message ,
So just clear current forms like below.
jQuery.ajax
({
type: "POST",
url: "<?php echo get_template_directory_uri() ?>/contact-form.php",
data: postvalues,
success: function(response)
{
jQuery('#status').addClass('success-
message').html(response).show().delay(2500).fadeOut();
// to clear all inputs
//jQuery("#contact-form input").val('');
jQuery("#contact-form input.requiredField").val('');
jQuery('#message').val("");
jQuery('input:not(#submit)').val("");
jQuery('#submit').attr('value', "Submit Message");
jQuery('#submit').removeAttr('disabled');
}
});
Hope its helps..
<?php
$al_options = get_option('al_general_settings');
$options = array(
$al_options['al_contact_error_message'],
$al_options['al_contact_success_message'],
$al_options['al_subject'],
$al_options['al_email_address'],
);
?>
<input type="hidden" name = "options" value="<?php echo implode(',', $options) ?>" />
Add new ID to the input and call it #options
<input id="options" type="hidden" name = "options" value="<?php.....
ADD #options to...
jQuery('input:not(#submit)').val("");
So now it reads...
jQuery('input:not(#submit, #options)').val("");
Bingo!

Categories