最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 plete
    {Send Email} 

echo "thank you for for your email"

}else{

Display email form

Solution i am trying?

<script src=".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><a href="#contact-form">Inquiry Form</a></li>
      </ul>
    </div>
    <div class='content one'>
      <div id="contact-form" class="clearfix">
        <?php

  if ($_POST["email"]<>'') { 
$ToEmail = '[email protected]'; 
$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"]."&nbsp;";
$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="ment">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>&nbsp;</p>
      <p>*Denotes a required field</p>
    </div>
  </fieldset>
  <?php
  };
  ?>
</div>
</div>
<script src=".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.

.php

The tab with the form is "enquiry form" in the menu.

I really hope someone can help?

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 plete
    {Send Email} 

echo "thank you for for your email"

}else{

Display email form

Solution i am trying?

<script src="https://ajax.googleapis./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><a href="#contact-form">Inquiry Form</a></li>
      </ul>
    </div>
    <div class='content one'>
      <div id="contact-form" class="clearfix">
        <?php

  if ($_POST["email"]<>'') { 
$ToEmail = '[email protected]'; 
$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"]."&nbsp;";
$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="ment">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>&nbsp;</p>
      <p>*Denotes a required field</p>
    </div>
  </fieldset>
  <?php
  };
  ?>
</div>
</div>
<script src="https://ajax.googleapis./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./SWCF/indextest2.php

The tab with the form is "enquiry form" in the menu.

I really hope someone can help?

Share Improve this question edited Jan 28, 2014 at 14:03 Dan Cundy asked Jan 28, 2014 at 13:02 Dan CundyDan Cundy 2,8692 gold badges40 silver badges65 bronze badges 2
  • The ajax success callback is called when your post request pletes. Use this callback to update the DOM and display your thank you message. – DaveRandom Commented Jan 28, 2014 at 13:06
  • change event.preventDefault(); to e.preventDefault(); – Pranav C Balan Commented Jan 28, 2014 at 13:06
Add a ment  | 

4 Answers 4

Reset to default 3

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) {

     }
   });
});
发布评论

评论列表(0)

  1. 暂无评论