How to get the sucess message in the same page after submitting the contact form?
Asked Answered
K

5

9

I have created the contact form using HTML and PHP. Also, the mail is coming correctly to mail id. But after the success message, it is redirecting to the form.php page can someone please help me. It is my first time trying to build a website.

Here is my code for contact form:

<form method="post" action="form.php">
    <input name="name" required="required" placeholder="Your Name">
    <input name="email" type="email" required="required" placeholder="Your Email">

    <div class="clearfix"> </div>
    <textarea name="message" cols="20" rows="5" required="required" placeholder="Message"></textarea>
    <div class="submit">
        <input id="submit" name="submit" type="submit" value="Submit">
    </div>
</form>

here is my form.php :

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: agriindiaexp.com'; 
$to = '[email protected]'; 
$subject = 'Email Inquiry';

$body = "From: $name\n E-Mail: $email\n Message:\n $message";

if ($_POST['submit']) {
    if (mail ($to, $subject, $body, $from)) { 
       $success = "Message successfully sent";
    } else {
        $success = "Message Sending Failed, try again";
    }
}
?>

Please help me.

Keishakeisling answered 5/12, 2016 at 6:54 Comment(7)
Check: https://mcmap.net/q/327851/-how-do-i-make-a-php-form-that-submits-to-selfGalasyn
If you want it without page refresh then check http://www.codingcage.com/2015/06/submit-php-form-without-page-refresh-jquery-ajax.htmlGalasyn
or <form method="post" action="/"> and add your form request php code to this pageFaience
I want it in the same page.Keishakeisling
@bhavya gvn after success message you want to redirect it to same page?or another page?Cockloft
@Shanu k k i want it to redirect it to the same pageKeishakeisling
please <form method="post" action=" " > or <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">try thisCockloft
D
6

try this way . try to send mail from an ajax . Please write your code like below

javascript

    <script type="text/javascript">
    function sendEnquiryform(){
        var name=$('#name').val();
        var email=$('#email').val();
        var message=$('#message').val();
        $.post("send_mail.php",'name='+name+'&email='+email'&message='+message,function(result,status,xhr) {
                if( status.toLowerCase()=="error".toLowerCase() )
                { alert("An Error Occurred.."); }
                else { 
                    //alert(result);
                    $('#sucessMessage').html(result);
                }
            })
            .fail(function(){ alert("something went wrong. Please try again") });
    }
</script>

Your html

<form method="post" name="FrmEnquiry" id="FrmEnquiry" action="" onsubmit="sendEnquiryform();">
    <input name="name" id="name" required="required" placeholder="Your Name">
    <input name="email" id="email" type="email" required="required" placeholder="Your Email">

    <div class="clearfix"> </div>
    <textarea name="message" id="message" cols="20" rows="5" required="required" placeholder="Message"></textarea>
    <div class="submit">
        <input id="submit" name="submit" type="submit" value="Submit">
    </div>
</form>

<span id="sucessMessage"> </span>

send_mail.php

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: agriindiaexp.com'; 
    $to = '[email protected]'; 
    $subject = 'Email Inquiry';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) { 
           $success = "Message successfully sent";
        } else {
            $success = "Message Sending Failed, try again";
        }
    }
?>

this will display your message in your page.Please try this. This is working fine in my case.

Disquietude answered 5/12, 2016 at 7:11 Comment(0)
F
3

You could post the form to the same page and check for a success message there, like this.

<?php

if ($_POST['submit']) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: agriindiaexp.com'; 
    $to = '[email protected]'; 
    $subject = 'Email Inquiry';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";
    if (mail ($to, $subject, $body, $from)) { 
       $success = "Message successfully sent";
    } else {
        $success = "Message Sending Failed, try again";
    }
}
?>

...other html....

<div id="message"><?php if(isset($success)){ echo $success; } ?></div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input name="name" required="required" placeholder="Your Name">
    <input name="email" type="email" required="required" placeholder="Your Email">

    <div class="clearfix"> </div>
    <textarea name="message" cols="20" rows="5" required="required" placeholder="Message"></textarea>
    <div class="submit">
        <input id="submit" name="submit" type="submit" value="Submit">
    </div>
</form>

...other html....
Fianna answered 5/12, 2016 at 8:18 Comment(0)
A
0

getting the error in java script.

function sendEnquiryform(){
        var fname=$('#fname').val();
        var email=$('#email').val();
        var pd=$('#pd').val();
        var pg=$('#pg').val();
        var ced=$('#ced').val();
        var score=$('#score').val();
        var message=$('#message').val();
        $.post("mail.php",'fname='+name+'&email='+email' +'&pd='+pd' +'&pg='+pg' +'&ced='+ced' +'&score='+score'&message='+message,function(result,status,xhr) } 
                if( status.toLowerCase()=="error".toLowerCase() )
                { alert("An Error Occurred.."); } 
                else { 
                    //alert(result);
                    $('#sucessMessage').html(result);
                }
            })
            .fail(function(){ alert("something went wrong. Please try again") });
    }
Apothecium answered 25/6, 2018 at 4:40 Comment(2)
Is this answer or question that you mentioned here?Cheffetz
This is questions i am facing issueApothecium
U
0

Using the mail.php on the same page where the form is could do the magic. the following code did the magic.

<?php

$from = '';
$sendTo = '[email protected]';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message');

$okMessage = 'Thank you for your message. I will write back soon.';
$errorMessage = 'There is an error while sending message. Please try again later.';

try {if (!empty($_POST)) {
    $emailText = "You have a new message from your contact form\n=====\n";
    foreach ($_POST as $key => $value) {
       if (isset($fields[$key])) {
         $emailText .= "$fields[$key]: $value\n";
       }
    }
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
 'From: ' . $from,
 'Reply-To: ' . $from,
 'Return-Path: ' . $from,
    );
    mail($sendTo, $subject, $emailText, implode("\n", $headers));
    $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e) {
  $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 $encoded = json_encode($responseArray);
 header('Content-Type: application/json');
 echo $encoded;
} else {
echo $responseArray['message'];
}


?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script>
    $(function () {
  $('#contact-form').on('submit', function (e) {
   if (!e.isDefaultPrevented()) {
    var url = "contact.php";

    $.ajax({
     type: "POST",
     url: url,
     data: $(this).serialize(),
     success: function (data) {
      var messageAlert = 'alert-' + data.type;
      var messageText = data.message;
      var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"> 
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times; 
</button>' + messageText + '</div>';
       if (messageAlert && messageText) {
       $('#contact-form').find('.messages').html(alertBox);
       $('#contact-form')[0].reset();
      }
     }
    });
    return false;

   }
  })
});
    </script>
</head>
<body>
<div class="container">
 <div class="row">
  <div class="col-xl-8 offset-xl-2">
   <h1>CONTACT FORM</h1><hr>
   <p class="lead">By filling out the contact form; You may have information about us and current news.</p>
   <form id="contact-form" method="post"  role="form" novalidate="true">
   <div class="messages"></div>
   <div class="controls">
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
        <label for="form_name">Full Name *</label>
        <input id="form_name" type="text" name="name" class="form-control" placeholder="Please fill the name field *" required="required" data-error="You must fill the name field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
       <label for="form_email">E-mail *</label>
       <input id="form_email" type="email" name="email" class="form-control" placeholder="Please fill the email field *" required="required" data-error="You must fill the email field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
     <div class="col-lg-6">
      <div class="form-group">
       <label for="form_subject">Subject *</label>
       <input id="form_subject" type="text" name="subject" class="form-control" placeholder="Please fill the subject field *" required="required" data-error="You must fill the subject field">
        <div class="help-block with-errors alert-danger"></div>
       </div>
      </div>
      <div class="col-lg-6"></div>
      </div>
     <div class="form-group">
      <label for="form_message">Message *</label>
      <textarea id="form_message" name="message" class="form-control" placeholder="Please fill the message field *" rows="4" required="required" data-error="You must fill the message field"></textarea>
       <div class="help-block with-errors alert-danger"></div>
      </div>
      <input type="submit" class="btn btn-success btn-send" value="Submit">
      <p class="text-muted" style="padding-top: 5px;"><strong>*</strong>This field must be fill.</p>
      </div><!-- controls all end -->
     </form><!-- form all end -->
    </div><!-- col-xl-8 offset-xl-2 end -->
   </div><!-- row all end -->
 </div><!-- container all end -->

</body>

Uppercut answered 3/1, 2020 at 11:25 Comment(0)
C
-1

Please use this code

<?php

if ($_POST['submit']) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: agriindiaexp.com'; 
    $to = '[email protected]'; 
    $subject = 'Email Inquiry';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";
    if (mail ($to, $subject, $body, $from)) { 
       $success = "Message successfully sent";
    } else {
        $success = "Message Sending Failed, try again";
    }

    echo $success;
}
?>
Carbide answered 5/12, 2016 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.