简体   繁体   中英

show ajax success or error message when form is submitted in the same page

I have a simple html form where I will send a mail and there is another file named as ajax-form-submit.php where the file process will do. Now I want to show the success or failure message in the html file through ajax. So my html form with jQuery goes like this

<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
  First Name: <input type="text" name="fname" value ="Ravi"/> <br/>
  Last Name: <input type="text" name="lname" value ="Shanker" /> <br/>
  Email : <input type="text" name="email" value="xx@xxx.com"/> <br/>
  <input type="button"  id="simple-post" value="Run Code" name="submit"/>
</form>

<div id="simple-msg"></div>

<script>
jQuery(document).ready(function() {
  jQuery("#simple-post").click(function() {
    jQuery("#ajaxform").submit(function(e) {
      jQuery("#simple-msg").html("<img src='loading.gif'/>");
        var postData = $(this).serializeArray();
        var formURL = $(this).attr("action");
        $.ajax( {
          url : formURL,
          type: "POST",
          data : postData,
          success:function(data, textStatus, jqXHR) {
            jQuery("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
          },
          error: function(jqXHR, textStatus, errorThrown) 
          {
          $("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
          }
      });
      e.preventDefault();  //STOP default action
  });

  $("#ajaxform").submit(); //SUBMIT FORM
});

});
</script>

Now the php file where the mail will go will be like this

<?php
if (isset($_POST['submit'])) { 
  $name = $_POST['name'];
  $lname = $_POST['lname'];
  $email = $_POST['email'];
  $ToEmail = 'test@demo.com';
  $MESSAGE_BODY = "Name: ".$_POST["name"]."<br>"; 
  $MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>";
  $mail = mail($ToEmail, $MESSAGE_BODY);
  if($mail) {
    echo "Mail sent successfully";
  }
  else {
    echo "oops there is some error";
  }
  }
?>

I want the success message or the error message should be shown in html page. Its showing only any message is written outside the if (isset($_POST['submit'])) { function but by doing this I can't show the success message or error message. So can someone kindly tell me how to do this? Any help will be really appreciable. Thanks.

HTML

<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
    First Name: <input type="text" name="fname" id="fname" value ="Ravi"/> <br/>
    Last Name: <input type="text" name="lname" id="lname" value ="Shanker" /> <br/>
    Email : <input type="text" name="email" id="email"  value="xx@xxx.com"/> <br/>
    <input type="button"  id="simple-post" value="Run Code" name="submit"/>
</form>
<div id="simple-msg"></div>

<script type="text/javascript">

jQuery("#simple-post").click(function() {

    jQuery("#simple-msg").html("<img src='loading.gif'/>");        
    var formURL = $(this).attr("action");
    var fname = $("#fname").val();
    var lname = $("#lname").val();
    var email = $("#email").val();
    $.ajax({
        url : formURL,
        type: "POST",
        data : {
            aFname: fname,
            aLname: lname,
            aEmail: email,
            aSubmit:"submit"
               },
        success:function(data, textStatus, jqXHR) {
            jQuery("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
        },
        error: function(jqXHR, textStatus, errorThrown){
            $("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
        }
    });
});
</script>


PHP

if (isset($_POST['aSubmit'])) {
    $name = $_POST['aFname'];
    $lname = $_POST['aLname'];
    $email = $_POST['aEmail'];
    $ToEmail = 'test@demo.com';
    $MESSAGE_BODY = "Name: ".$_POST["aFname"].' '.$_POST["aLname"]."<br/>"; 
    $MESSAGE_BODY .= "Email: ".$_POST["aEmail"]."<br/>";
    $mail = mail($ToEmail, $MESSAGE_BODY);
    if($mail) {
        echo "Mail sent successfully";
    }
    else{
        echo "oops there is some error";
    }
}

Note :_ I would like to mention here that i have not shown any efforts to prevent SQL injection or any other kind of vulnerability-prevention here just because that can increase the complexity for you. But, make sure that before posting such code to live sites, you incorporate all efforts to prevent your site. _

I would suggest to send the status (success or error) back to the client using JSON (using PHP json_encode()). For that, you will also need to add a JSON listener in your page using JQuery script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM