What is possible with event.PreventDefault() and ajax POST method? - javascript

Problem?
I have a problem where i can't use a normal HTML POST as it refreshes my webpage causing a JS controlled 'Tab' to close. Thus forcing the user to reopen the tab to see the feedback from the submitted form.
How it should work
The user enters their data into the form and then clicks submit, the form POSTs the data to itself, emailing the data to an email address. once the data is sent a message should replace the form saying the email had been sent. (all without the tab that contains the form closing)
Sudo Code
If (email) is complete
{Send Email}
echo "thank you for for your email"
}else{
Display email form
Solution i am trying?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><script>
$('#form1').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'indextest2.php',
data: $("#form1").serialize(),
success: function(response) {
}
});
});
</script>
Now this would be great as it stops the page refreshing and it sends the email but it stops the "thank you you message has been sent" html from replacing the form.
So for all intents and purposes the user doesn't know if the email has been sent as the form is still there displaying the data they inputted.
Possible workaround?
Somehow getting the ajax post to insert the "thank you" message into the correct div on success of ajax post?! Is this possible?
Or am i doing something wrong, implementation wise?!
Actual Code I'm using
<div id="tabsContainer">
<div class='tab one'>
<ul>
<li>Inquiry Form</li>
</ul>
</div>
<div class='content one'>
<div id="contact-form" class="clearfix">
<?php
if ($_POST["email"]<>'') {
$ToEmail = 'dancundy#hotmail.com';
$EmailSubject = 'EasyScrap Enquiry';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["FName"]." ";
$MESSAGE_BODY .= $_POST["SName"]."<br>";
$MESSAGE_BODY .= "Tel: ".$_POST["CTNumber"];
$MESSAGE_BODY .= "<br>"."email: ".$_POST["email"]."";
$MESSAGE_BODY .= "<br>"."Address: ".$_POST["STName"]." ".$_POST["PCode"];
$MESSAGE_BODY .= "<br>"."Comment: ".nl2br($_POST["Comment"])."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
<h3>Contact Us</h3>
<P>Your message was sent, thank you! You will recieve an automated response within the next few minutes and will hear back from a Plymouth Easy Scrap representive shortly.</P>
</div>
</div>
</div>
<?php
}else{
?>
<fieldset>
<legend>
<h3>Contact Us</h3>
</legend>
<div id="contact-area">
<form id="form1" method="post" action="">
<label for="FName">Name:*</label>
<input name="FName" type="text" required placeholder="Enter your name" />
<label for="SName">Surname:</label>
<input name="SName" type="text" placeholder="Enter your surname" />
<label for="STName">Street:</label>
<input name="STName" type="text" placeholder="Enter the address" />
<label for="PCode">PostCode:</label>
<input name="PCode" type="text"placeholder="UK Postcode" />
<label for="Email">Email:*</label>
<input type="email" name="email" required placeholder="Enter a valid email address"/>
<label for="CTNumber">Contact:</label>
<input name="CTNumber" type="text" placeholder="Enter a contact number"/>
<label for="comment">Message:</label>
<br/>
<textarea name="Comment" rows="20" cols="20" id="Message"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
<div class="FormInfo">
<p> </p>
<p>*Denotes a required field</p>
</div>
</fieldset>
<?php
};
?>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><script>
$('#form1').submit(function(e)
{
event.preventDefault();
$.ajax({
type: 'POST',
url: 'indextest2.php',
data: $("#form1").serialize(),
success: function(response) {
}
});
});
</script>
Here is the actual site which will give you a better idea what i mean when i say 'tab' and hopefully expand on the problem more.
http://www.cundytech.com/SWCF/indextest2.php
The tab with the form is "enquiry form" in the menu.
I really hope someone can help?

once the messsage is sent , replace the form with the thank you message.
this could be done by replacing the dom structure containing the form with the thank you message within ajax success block
ajax code:
$('#form1').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'indextest2.php',
data: $("#form1").serialize(),
success: function(response) {
// replace the email form with thank you message
$('#targetForm').html("<div class="info">Thank you for your message !!!<div>");
}
});
});
Happy Coding :)

Solution
The Solution posted by #deamweiver worked a treat. Using the Success part of the ajax post function i was able to swap out the form for a thank you message after successfully posting form data.
This is the code needed
('#form1').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'indextest2.php',
data: $("#form1").serialize(),
success: function(response) {
$('#form1').html("<div class=\"info\">Thank you for your message !!!<div>");
}
});
});

Try following things:
indextest2.php page:
function index(){
//Do whatever receiving the data
if(Your job is done){
echo "Success";
}else{
echo "Error";
}
}
ajax Call:
$(document).ready(function(){
$('#form1').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'indextest2.php',
data: $("#form1").serialize(),
success: function(response) {
if(response=="Success"){
$('#contact-area').html("<div>thank you you message has been sent</div>")
}else{
$('#contact-area').html("<div>Sorry Something went Wrong !</div>")
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr.responseText);
}
});
});
The e you are using here is the event that generates after submitting the form or clicking the submit button. Then the browser refresh and goes to the action="" url that you have entered in form tag. Whenever you use e.preventDefault than it stops the action of form submission and does the code you write below of e.preventDefault. Generally people use preventDefault to stop refreshing browsers on a tag and submit buttons of form. Good Luck.

what is event in your javascript?
In your argument you use event and in the function body you use e.
argument and variable must be same.
For your solution it should be e.
Following code may help you...
$('#form1').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'indextest2.php',
data: $("#form1").serialize(),
success: function(response) {
}
});
});

Related

How to get php page to receive ajax post from html page

I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.

Why does my jQuery code POST return a query string in my URL?

So I've followed some guides online and made a simple jQuery POST.
$("#btnLogin").click(function () {
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "http://localhost:8080/OhSnip/api/users/",
dataType: "application/x-www-form-urlencoded",
data: {
username: username,
password: password,
},
success: function(result) {
console.log(result);
}
})
});
However, whenever I click the login button, the page returns a query string and completely ignores the success function, writing nothing on the console.
http://localhost:8080/OhSnip/?username=username&password=password.
Why does this happen?
I've tried many different formats and whatnot, but I have been unable to solve this issue by myself so far.
Tutorials on youtube aren't really helping either.
The backend works fine, as you can see from the picture above, but here's the code anyway
#POST
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.APPLICATION_JSON)
public User logIn(
#FormParam("username") String username,
#FormParam("password") String password) {
UserManager um = UserManager.getInstance();
return um.logIn(username, password);
}
Anyway, thanks.
EDIT: Form html code.
<form id="logIn" action="">
<div class='form-group'>
<label for='username' class='sr-onl'>Username</label>
<input id='username' type='username' required='' placeholder='Username' class='form-control' name='username'>
</div>
<div class='form-group'>
<label for='password' class='sr-onl'>Password</label>
<input id='password' type='password' required='' placeholder='Password' class='form-control' name='password'>
</div>
<div class='form-group'>
<button id="btnLogin" class='btn btn-block'>Login</button>
</div>
</form>
When you are using AJAX, the URL in the script overrides any URL that's in the form action attribute, but you can use
<form id="logIn" action="javascript:void(0);" method="POST">
You do need the e.preventDefault() in the button function and the POST method on the form as you do in your second example. Otherwise the default behaviour of a button within an HTML form is to submit the form as a regular GET request, in which form values are attached to the URL as a query string. The e.preventDefault() is necessary to tell the form to follow the script instead of submitting the usual way and the method="POST" tells the form it's a POST request not GET.
https://www.w3schools.com/tags/ref_httpmethods.asp
Turns out it was an HTML form problem as Jwebb suggested.
I added the action and the method parameters to the form.
<form id="logIn" action="api/users" method="POST">
<div class='form-group'>
<label for='username' class='sr-onl'>Username</label>
<input id='username' type='username' required='' placeholder='Username' class='form-control' name='username'>
</div>
<div class='form-group'>
<label for='password' class='sr-onl'>Password</label>
input id='password' type='password' required='' placeholder='Password' class='form-control' name='password'>
</div>
<div class='form-group'>
<button id="btnLogin" class='btn btn-block'>Login</button>
</div>
</form>
Aswell as the event.preventDefault() function to the submit button
$("#btnLogin").click(function (e) {
e.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "http://localhost:8080/OhSnip/api/users/",
data: {
username: username,
password: password,
},
})
.done(function(result) {
console.log(result)
})
});

Clear form field after submit

I have read other answers for the same question but I am having problems and would be grateful for some advice.
I have javaScript in my html file, and an Onclick() statement on the submit button to clear the form but now the email confirmation message does not come up and the message is no longer sent. If I put the onClick(); in the body of the form, every field is cleared just by clicking on a form field. I really want to be able to submit a message, then have the form cleared on successful send.
<script type ="text/javascript">
function clearform () {
document.getElementById("name").value="";
document.getElementById("email").value="";
document.getElementById("subject").value="";
document.getElementById("message").value="";
}
</script>
<div class="row">
<div class="col-sm-6">
<h2>Send us a message</h2>
<!-- action="replace it with active link."-->
<form action="contact.php" method="post" name="contact-form" id="contact-form" >
<label for="name">Your Name <span>*</span></label>
<input type="text" name="name" id="name" value="" required />
<label for="email">Your E-Mail <span>*</span></label>
<input type="text" name="email" id="email" value="" required />
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" value="" />
<label for="message">Your Message</label>
<textarea name="message" id="message"></textarea>
<div class="row">
<div class="col-sm-6">
<input type="submit" name="sendmessage" id="sendmessage" value="Submit" onclick="clearform();" />
</div>
<div class="col-sm-6 dynamic"></div>
</div>
</form>
I then have the following in the PHP file:
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
//$this->response_html = '<p>Thank You!</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span>";
header("Location: contact.php");// redirect back to your contact form
exit;
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
No ajax form post
If you are not using ajax to submit the form (you don't seem to be using it), there is no need for javascript to clear the form, the form will be reloaded on submit and it will be empty.
However, you have a problem with your location redirect: You are outputting html before that so the redirect will probably fail.
You should not output anything before you redirect and you could add a query variable to the url so that you can show your success message when the form loads:
if($this->response_status)
{
$this->sendEmail();
}
header("Location: contact.php");// redirect back to your contact form
exit;
Using ajax to post the form
If you are using ajax (the setting of your response variables seems to indicate that you want to do that), you should put the clearform () call in the success function of your ajax call and remove the header() redirect in php. Instead you probably want to return / output the results:
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
exit;
You've got to make sure the event continues to propagate and the form is submitted:
function clearform () {
document.getElementById("name").value="";
document.getElementById("email").value="";
document.getElementById("subject").value="";
document.getElementById("message").value="";
return true;
}

Set error button when i enter repeated invalid email or blank entry in subscribe form in jquery

I have been created subscribe form using php and jquery and sql to store data.
Now it is working fine, but it has some limitation.
When i enter invalid email address, it shows like this,
But i need to remove that message, i need only working effects with error button.
And If i enter blank, that time error button working fine[that is button will be shaken and says error], after that i enter valid address, it also working fine[that is success button].
One more think, if i enter invalid address at first, and second also enter invalid address,, the error button works fine at first time only.
Here is lib.js:
$(document).ready(function () {
$('#newsletter').submit(function () {
var $this = $(this),
$response = $('#response'),
$mail = $('#signup-email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$('#actbtn').removeClass('btn-error').addClass('btn-error');
//$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize(),
success: function(data){
if(data!=''){
$response.removeClass('loading');
if(data.status == 'success'){
$('#actbtn').removeClass('btn-error').addClass('btn-success');
}
else{
$('#actbtn').removeClass('btn-error').addClass('btn-error');
}
}
}
});
}
return false;
});
});
html:
<div id="newsletterform">
<div class="wrap">
<h3>Get Email Update</h3>
<form action="send.php" method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<button id="actbtn" class="btn btn-7 btn-7h icon-envelope">Submit form</button>
<span class="arrow"></span>
</form>
<div id="response"></div>
</div>
</div>
May i know,how to achieve this one, Any idea would be highly appreciated.
Thanks in advance.
You have used the
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
try to use it as input text because you did the script validation
<input type="text" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />

jQuery If/else statement that adds text to DIV upon successful form submit

I have a form built that works perfectly fine. However, when a message is successfully submitted, the user gets redirected to a new page with the 'success' message I have set up. Instead, I want the success message to be displayed in a div which is placed next to the form, and the form to reset in case the user would like to send another message. Likewise, I am also hoping to have my 'error' message show up in the same div upon failure. Was hoping someone can help with my if/else statement to make this possible.
Here's my HTML:
<div id="contact-area">
<form id="theform" name="theform" method="post" action="feedback.php">
<input type="hidden" name='sendflag' value="send">
<p>
<label for="Name">Name:</label>
<input type="text" name="name" id="name" value="" />
</p>
<p>
<label for="Email">Email:</label>
<input type="text" name="email" id="email" value="" />
</p>
<p>
<label for="Message">Message:</label><br />
<textarea name="message" rows="20" cols="20" id="message"></textarea>
</p>
<p>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</p>
</form>
</div>
<div class="message">
<p class="submitMessage"></p>
</div>
Here's my PHP:
<?php
$mail_to_send_to = "myemail#gmail.com";
$your_feedbackmail = "noreply#domain.com";
$sendflag = $_REQUEST['sendflag'];
if ( $sendflag == "send" )
{
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$headers = "From: $name" . "\r\n" . "Reply-To: $email" . "\r\n" ;
$a = mail( $mail_to_send_to, "Feedback form", $message, $headers );
if ($a)
{
print("Message was sent, you can send another one");
} else {
print("Message wasn't sent, please check that you have changed emails in the bottom");
}
}
?>
If I understand your question correctly, you're looking to never leave a page but rather have a div appear or disappear based off of a successful form submission. If so, it looks like you're going to have to use AJAX. Luckily, jQuery has this built right in! I'd suggest something like the following:
$.post("url.php", { option1: value1, option2: value2 }, function(data) {
if(data != '')
$('#theDiv').html("Success!");
});
For more information, read up on the documentation here.
Read and follow examples here: jQuery AJAX
You'll basically do something like this.
$.ajax({
url: /url/to/your/php,
data: dataObjectPosting
success: function(data){
//the data object will have your PHP response;
$('#divid').text('success message');
},
error: function(){
alert('failure');
}
});
Remember, success simply means HTTP 200, not necessarily that your PHP code ran successfully as you would see it.

Categories

Resources